pointer

Can any one explain how the below program works? Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
    int *p=(int *)1000;
    int *temp;
    temp = p;
    p=p+6;
    printf("\n%u %u",temp,p);
    printf("\nDifference is %d",p-temp);
    return 0;
}

output:
1000  1024
Difference is 6
Create pointer named p. Make it point to memory location 1000.
Create pointer named temp. Make it the same as p.
Move the pointer p along six*(sizeof an int) - this is "pointer arithmetic".
Print out the value of the two pointers (ie. the numbers of the memory locations they point at).
Print out the value of p minus temp (which is more pointer arithmetic - the answer comes out as six because these are int pointers, and on this system the size of an int is 4 bytes, so a difference in memory location of 24 is 24/4=6 int values).
Last edited on
pointer of type int * ( for example int *p; ) points integers. Each integer of type int usually occupies 4 bytes. Then you are incresing a pointer of type int * it begins to point a next integer. That is if initial value of p is equal to 1000 then ++p will point to 1000 + sizeof( int ) <==> 1000 + 4 <==> 1004

++p is equivalent to p + 1. So p + 6 is equivalent to 6 times by sizeof( int ) that is equal to 24.
Topic archived. No new replies allowed.