In C, a pointer is just a variable whose value is address of another variable. We declare a pointer like this: data_type *variable_name;
Example:
Here we declared an integer pointer, which means ptr will store the address of an integer variable. To get the address of a variable, we use the & operator like this: &variable_name.
Example:
Here we are getting the address of x and storing it in the pointer ptr.
To retrieve the value stored at the memory location that is pointed by the pointer, do this: *pointer_name.
Example:
Taking the address of an existing variable is called referencing and getting the value at an address by following the pointer i.e. going to that address and getting the value is called dereferencing.
Let’s look at a simple example of where pointers are useful.
Explanation:
- swap function does not take integers here. It takes 2 integer pointers i.e. addresses of 2 integer variables.
- While calling the function swap in main, we are passing the addresses of variables a and b to it.
- temp stores the value at first address. We first go to the address that is stored in x, then get the value that is stored there and save it in variable temp. So now temp is 10.
- Then we go to the address of first integer (a) and set its value to be the value of second integer. We go the the address stored in y, get the value from there and save at in a’s address (remember that x is just the address of a). So a will be now 20.
- Then we go to the address of second integer (b) and set its value to be temp i.e 10. So now b is 10.