#include<stdio.h> int main(){ int a,b; int *ptr1,*ptr2; a=5; // Assigns value 5 to a b=a; // Assigns value of a (i.e., 5) to b ptr1=&a; // Assigns address of a to prt1 or ptr1 points to variable a ptr2=ptr1; // ptr2 holds same address as ptr1 does (i.e, address of a) b=(*ptr2)++; /* Now this one is tricky. Look at precedence table here http://en.cppreference.com/w/cpp/language/operator_precedence b is assigned value of *ptr2 first and then value at *ptr2 (i.e., 5) is incremented later. Try replacing b = (*ptr2)++ with b = ++(*ptr2). It'll print 6. */ printf("a = %d, b=%d,*ptr1=%d,*ptr2=%d\n",a,b,*ptr1,*ptr2); }
Let's visualize through address and value table. Suppose int is 1-byte or 1-unit and address space of your program begins with 100.
a = 5 a +---+---+---+---+---+-- | 5| | | | | ... +---+---+---+---+---+-- 100 101 102 103 104 ... b = a a b +---+---+---+---+---+-- | 5| 5| | | | ... +---+---+---+---+---+-- 100 101 102 103 104 ... ptr1=&a a b ptr1 +---+---+----+----+---+-- | 5| 5| 100| | | ... +---+---+----+----+---+-- 100 101 102 103 104 ... ptr2 holds some random address when you initialize. int *ptr2; a b ptr1 ptr2 +---+---+----+----+---+-- | 5| 5| 100| 234| | ... +---+---+----+----+---+-- 100 101 102 103 104 ... ptr2=ptr1 a b ptr1 ptr2 +---+---+----+----+---+-- | 5| 5| 100| 100| | ... +---+---+----+----+---+-- 100 101 102 103 104 ... b=(*ptr2)++ First, dereference *ptr2 and assign that to b. a b ptr1 ptr2 +---+---+----+----+---+-- | 5| 5| 100| 100| | ... +---+---+----+----+---+-- 100 101 102 103 104 ... ^ | |____________| Now increment value at address 100 a b ptr1 ptr2 +---+---+----+----+---+-- | 6| 5| 100| 100| | ... +---+---+----+----+---+-- 100 101 102 103 104 ...
Hope that vizulization helps.
Read about pointer assignment here : C++ pointer assignment
b=(*ptr2)++;That takes whatptr2is pointing to and increments it after accessing its value.x++and++x.b = (*ptr2)++;is basicallyb = *ptr2; (*ptr2)++;or in this caseb = a; a++;read about the post increment operator.(*ptr2)accesses the value of whatptr2is pointing to; 2)bis set to that value; 3) since you have post increment, afterbis set to 5, then that value of whatptr2is pointing to is incremented by 1 and is now 6. If you had++(*ptr2)instead, then the value would be accessed, incremented, then assigned tob