Darla SandyKnowledge Contributor
What is a pointer? give examples
What is a pointer? give examples
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Questions | Answers | Discussions | Knowledge sharing | Communities & more.
A variable that holds the address of another variable is called a pointer. A pointer stores the address of a variable, as opposed to other variables that store values of a certain kind.
For instance, an integer pointer carries the address of an integer variable, but an integer variable retains—or more accurately, stores—an integer value.
A pointer is a variable in programming that stores the memory address of another variable. In simpler terms, it “points to” the location of another variable in memory rather than storing a value directly. Pointers are fundamental in languages like C, C++, and other low-level languages where direct memory manipulation and efficiency are important.
Here’s an example in C:
#include
int main() {
int num = 10; // declaring an integer variable
int *ptr; // declaring a pointer variable
ptr = # // assigning the address of num to ptr
printf(“Address of num: %p\n”, &num); // printing the address of num
printf(“Value of ptr: %p\n”, ptr); // printing the value of ptr (which is the address of num)
printf(“Value at ptr: %d\n”, *ptr); // printing the value at the address stored in ptr
return 0;
}
Explanation of the example:
int num = 10;: Defines an integer variable num with a value of 10.
int *ptr;: Declares a pointer ptr to an integer (int * denotes a pointer to an integer).
ptr = #: Assigns the address of num to ptr using the address-of operator (&).
printf(“Address of num: %p\n”, &num);: Prints the address of num using %p format specifier.
printf(“Value of ptr: %p\n”, ptr);: Prints the value stored in ptr, which is the address of num.
printf(“Value at ptr: %d\n”, *ptr);: Prints the value at the address stored in ptr using the dereference operator (*ptr), which accesses the value at the memory address ptr points to (num in this case).
In this example, ptr is a pointer that “points to” the variable num, allowing us to indirectly access and manipulate num through ptr. Pointers are powerful tools for efficient memory management and data manipulation in programming languages that support them.