Tuesday 17 November 2015

All About Pointers

Definition:In computer science, a pointer is a programming language object, whose value refers to (or "points to") another value stored elsewhere in the computer memory using its address. A pointer references a location in memory means a pointer points to address.
When we declare int num=20; then this declaration tells the C compiler to :
1- Reserve space to hold Integer value.
2- Associate a name (here num) with this memory location
3- Store the value 20 at this location.

So by above figure it is cleared that location number is also a number itself. It is not fixed so it may change when you re-run your application.

Address can not be negative and that is the reason for using unsigned integer or %u as format specifier.
Any discussion is incomplete without program. So let us write a program to print a variable's value and its address:

#include<stdio.h>
int main()
{
      int num=20;
      printf("Value of num is = %d",num);          /*we get value as 20*/
      printf("Address of num is = %u",&num);  /*we get address as 65524 (Not fixed)*/
      printf("Value of *(&num) is = %u",*(&num)); * we get 20 */
}
Now let's go to intricacies  of our program.
  • value of num is 20
  • &num gives address of memory location where num is present. '&' is called 'address of' and '*' is called value at address. So if we are doing this *(&num), It means we are saying that we want to know the value that is present on address of num. Obviously if we go to address of num we find value num there. So, *(&num) = num. 
Now if we want to store the address of num to a variable itself we can not simply do like int getAddress=&num  because getAddress is not an ordinary variable. It is a variable that contains the address of another variable. So we have to write it as,
int * getAddress = &num;
Also note that getAddress itself is a variable so it should also have address that is generated by compiler. So if we want to hold address of getAddress pointer, all we have to do:
int * * addressOfPointer = &getAddress;



No comments:

Post a Comment