Tuesday 3 January 2012

Pointers


C pointer is a memory address.
The ‘*’ And ‘&’ Operators
Take a look on the following declaration,
                int x=10;
When we make such declaration how C compiler treat this statement:
1)Reserve memory space for this integer value.
2) Name this memory location as x.
3)Store the value 10 at this location.
This can be illustrated by a simple diagram:

                        Integer variable location in memory.So when we declared an integer variable x and assigned value 10 then compiler occupied a 2 byte memory space at memory address 65325 and stored value 10 at that location. Compiler named this address x so that we can use x instead of 65325 in our program. But we can use address or variable in our program and both will point to the same value (example given below).The memory address of a variable could differ from PC to PC and entirely depends on available free space in memory at time of program execution. As this differs from PC to PC thus we cannot rely on that address (numeric value representing variable address) and we cannot use this address in our program. But have you noticed one thing that address is an integer.We can print address of any variable or function, following program shows how we can do that:Address of variable example.
#include<stdio.h>#include<conio.h> void main(){    int i=9;   
    clrscr();
     printf("Value of i : %d\n",i);    printf("Address of i : %u",&i);     getch();
}
This is a very simple c program which prints value and address of an integer. .
Value at address (*) example
#include<stdio.h>
#include<conio.h>
 void main()
{
    int i=9;
    clrscr();
     printf("Value of i : %d\n",i);
    printf("Address of i : %u\n",&i);
    printf("Value at address of i : %d",*(&i));
     getch();
}
                                                             Output of "value at address" operator example.

No comments:

Post a Comment

host gator coupon