A pointer variable is a variable that holds the memory address of another variable. They are called pointers for the simple reason that, by storing an address, they point to a particular location in memory.
At the moment when a variable is declared, it must be stored in a concrete memory location. The programs do not decide where the variable is to be placed. That is done automatically by the compiler and the operating system at run time.
The declaration int x=3 tells the C compiler to
- Reserve space in memory to hold the integer value.(location/address is decided by the compiler/os)
- Associate the name x with this memory location.
- Store the value 3 in this location.
The value stored can be obtained with
The memory location or address can be obtained with
printf(“%u”,&x); // &x is the address of the variable x.
The pointer variable is declared with *(indirection) operator.
int *p; creates a pointer variable p which can store the address of an integer variable.
p=&x ; now p contains address of integer variable x ie; p points to variable x.
Because a pointer holds an address rather than a value, it has two parts.
The pointer itself holds the address.
The address points to a value.
printf(“%u”,p) will print the address it holds
printf(“%d”,*p) will print the value it points to
pointers can be used to
- Build faster and efficient code.
- Alternate/efficient way of accessing information stored in variables and arrays.
- Pass arrays and strings more conveniently from one function to another.
- Return more than one value from a function
- Dynamic memory allocation.
- Build complex data structures.( linked lists, trees etc..)
The following program will illustrate the pointer indirection operator and dereferencing
printf(“the value and address of num is %d %u”,num,&num);
printf(“the value and address of num using pointer ptr is %d %u”,*ptr,ptr);
*ptr=15; // indirection, which stores value in variable num using the pointer ptr.
printf(“the value of num after indirect initialization is %d”,num);