A pointer is a special type of variable that stores the memory address of another variable.
Pointer declaration in C is similar to variable declaration except that the variable name is preceded with an asterisk(*). A pointer is also associated with a type which declares what type of value it points to.
int *ptr;
In the above example ptr
is the name given to the pointer. The *
before ptr tells the compiler to treat it as a pointer variable. Finally the int
declares that the pointer points to an integer variable.
A pointer is normally initialized using the &
operator (address-of operator). The address-of operator returns the address of a variable.
int i = 10; int *ptr; ptr = &i;
In the above example, the address of variable i
is assigned to the pointer variable ptr
.
The pointer variable ptr
in the example above contains the memory address of variable i
. The value stored in that memory address can be obtained by preceding the pointer variable with the * operator, as in *ptr
. This is called dereferencing.
#include <stdio.h> int main() { int i = 10; int *ptr; ptr = &i; printf("i = %d\n", i); printf("ptr = %x\n", ptr); printf("*ptr = %d\n", *ptr); return 0; }
The output of this program will be as below. Please note the value of ptr
may change every time you execute the program as this is memory address of variable i
i = 10 ptr = 20fa50 *ptr = 10
Nothing yet..be the first to share wisdom.