Pointers
A pointer is a variable that stores memory address. Like all other variables it also has a name, has to be declared and occupies some spaces in memory. It is called pointer because it points to a particular location.
Consider the declaration
int i = 9; this tells the C compiler to
- Reserve space in memory to hold the integer value.
- Associate the name i with memory location.
- Store the value i at this location.
i → Location name
9 → Value at location
12354 → Location number or address
# include <stdio.h>
void main ( )
{
int i = 9;
printf (“\n Address of i = % &i );
printf (“\n Value of i =%d”, *(&1));
}
‘&’ = Address of operator
‘*’ = Value at address operator or ‘indirection’ operator &i returns the address of the variable i.
* (&i ) return the value stored at a particular address printing the value of *(&i) is same as printing the value of i.
Key Points
- If we want to assign some address to some variable, then we must ensure that
the variable which is going to store some address must be of pointer type. - If we want to assign &i to j e. j = &i; then we must declare j as int *j;
- This declaration tells the compiler that j will be used to store the address of an integer value or j points to an integer.
int * j; means the value at the address contained in j is an integer.
Pointers are variables that contain addresses and since addresses are always whole numbers. Pointers would always contain whole numbers.
int i = 3; i j
int *j; 3 65524
j = &i ; 65524 65522
i ‘s value is 3 and j’s value is 1 ‘ s address.
printf (” \n Address of i = %u”, &i );
printf (“\n Address of i = %u”, j);
Output Address of i = 65524
Address of i = 65524
printf (“In Address of j = %u” , & j);
printf ( ” /nvalue of j = %u” ,i);
Output Address of j = 65522
Value of j = 65524
printf (“\n Value of i = %d”, *(&–i )) ;
printf (“\n Value of i = %d” *j
Output Value of i = 3
Value of i = 3