It is basically address of a variable in memory. It allows us to indirectly access a variable. So using pointers we can talk about a variable's address(as well as its value by dereferencing the pointer). They are useful when we want to deal with address of a memory location rather than its value.
Consider the following simple swap function in C:
void Swap(int firstVal, int secondVal)
{
int tempVal = firstVal;
firstVal = secondVal;
secondVal = tempVal;
}
now in main if we have the following code:
.
.
int a = 9,b = 100;
swap(a,b);
//print a and b
.
.
The values of a and b would remain unchanged as would be clear by printing their values in the main function. To implement the swap function correctly, instead of passing the values of variables a
and b
, we pass the address of variables a and b as:
swap(&a,&b);
The operator &
, returns the address of the variable. Its used like this:
int *address_of_a = &a;
the int *address_of_a
, states that the variable address_of_a
points to(stores the address of) an integer variable.
Now our correct swap function would be:
void Swap(int *firstaddress, int *secondaddress)
{
int tempVal = *firstaddress;
*firsaddress = *secondaddress;
*secondaddress = tempVal;
}
Now the interchanged values would be reflected in main function:
int a = 9,b = 100;
swap(&a,&b);
//print
You can always dereference the pointer using *
, if you dont have the original variable. Suppose if in a function you do not have the original variable but have its address in a pointer variable int *x
. We can simply access the value of the memory address as value = *x
;
If we did not have pointers we could never emulate pass by reference in C
, because C
is pass by value. But remember we can only emulate, because even when we use pointers, the int *firstaddress, int *secondaddress
are only local pointer variables created, that have the address of variables a
and b
.