Hi Amrit, I'll try to explain it with some diagrams. First, the simple case - you probably know this, but I'll show it for completeness. The class Foo has a single member of type int (int32), so it has a size of 4 bytes.
# 3 instances of Foo in memory with a Foo* pointer pointing to it:
Foo myFoo[3]; // in _tmain(..)
Foo* ptr = myFoo; // calling display(..) (I renamed *obj to *ptr here)
ptr ptr+1 ptr+2 // the loop in display(..)
(100) (100+4) (100+8)
| | |
v v v
Memory address: 100..103 104..107 108..111 // (artificially chosen address)
Instance: --Foo1-- --Foo2-- --Foo3--
Members: ---i---- ---i---- ---i----
Now with the class Bar (8 bytes) and your original approach:
# 3 instances of Bar in memory with a Foo* pointer pointing to it:
Bar myBar[3]; // in _tmain(..)
Foo* ptr = myBar; // calling display(..)
ptr ptr+1 ptr+2 // the loop in display(..)
(100) (100+4) (100+8) // here's why it doesn't work:
| | | // ptr is Foo* so ptr+1 still means adding the size of Foo (4) !
v v v
Memory address: 100........107 108........115 116........123
Instance: -----Bar1----- -----Bar2----- -----Bar3-----
Members: ---i---___j___ ---i---___j___ ---i---___j___
Value: 0 1 0 // and there's your strange output! ;-)
And now with pointers to pointers. Let's say we're on a 32bit-system here, then a pointer has the size of 4 bytes (32 bit). So, when doing pointer arithmetic with pointers to pointers, adding 1 means always increasing its pointed-to-address by 4 bytes. It doesn't have anything to do with the size of the class that's being pointed to by the pointer that's being pointed to :-D
# 3 instances of Bar in memory with a Foo** pointer pointing to Bar* pointers:
Bar myBar[3]; // in _tmain(..)
Foo *myBaz[3] = { &myBar[0], &myBar[1], &myBar[2] };
Value: 100 108 116
Foo** pptr = myBaz; // calling display2(..) (for clarity, I named it pptr here)
pptr pptr+1 pptr+2
(200) (200+4) (200+8) // see explanati