Pages

Friday, November 19, 2010

Pointers

What is a pointer
You must have seen sign boards, arrows pointing towards a shop, mall or office. Such signs help the visitors in reaching the place correctly. All such boards or signs which are used to "point" to any building are actually "pointers" to something like office or shop. The same task is performed by C pointers by "pointing" to the location of a variable in memory. A pointer technically is a variable which points to or stores the address of another variable in the memory or RAM. The difference between a pointer variable and a normal variable is that a normal variable stores "normal" values like someone's name, address,telephone number or any other value which the user wants it to store, a pointer on the other hand does not store such values instead it stores memory address of any variable in the memory.

Why is it needed
You must be aware of the fact that the RAM is divided into rows and columns where each intersection (i.e., cell) is a memory block where data is stored. When we declare a variable say "int x", the compiler first reads the data type (which is 'int' in this case) and then sets aside a particular amount of memory required to store this variable in memory. For example, when it sees that the variable is of "int" type, it allocates 2 bytes of memory for the data that we will stored and labeled as "x".  The compiler does not internally refers to the memory locations as a, b , c, etc. instead the addresses are in hexadecimal form.
These hexadecimal addresses are difficult to remember and moreover, are not known previously to anybody, therefore to make their calling easy we are provided with the facility of naming them using friendly names like marks,salary,data etc., which are the variable names. So to say that what we refer to it as price,days,income etc. are the easy names of complex memory addresses. Coming back to memory addresses each variable is assigned a unique memory address allocated by the OS. For example, if there is a declaration such as :

        int marks;

the compiler will label a memory block with the name "marks". When we initialise a value in the
this variable, using a statement like
        marks = 80;
There are actually two "values" associated with the variable marks. One is the value of the
integer stored there (2 in the above example) and the other the "value" of the memory
location, i.e., the address of marks. The two values are also called
rvalue (right value) and lvalue (left value) respectively. Don't forget that in C, the assignment is always made to the variable on the left side of the assignment operator (=).

0 comments:

Post a Comment