0

I have a pointer to array, why it gives me the following output?

int main() {
    int b[] = {1, 2};
    cout << "size of int = " << sizeof(int) << endl;
    int *pt = b;
    int i = 0;
    while( i++ < 2) {
        cout << "pt = " << pt << ", b = " << b << endl;
        cout << pt - b << endl;
        (pt)++;
        }
    return 0;
}

code output:

size of int = 4
pt = 0x7fff576f0c2c, b = 0x7fff576f0c2c
0
pt = 0x7fff576f0c30, b = 0x7fff576f0c2c
1

pt is a pointer to the start of array b initially, why pt-b gives me the index of the array that pt points to rather than the index of the array times the size of one element.

2 Answers2

-1

it's because your array is really an address, and int *pt = b; essentially makes pt the exact same as b

your output is simply printing the number of times you've incremented pt since you set it to b

-1

Remember, in the end, pointers are plain old ints, which represent an address in your logical space. Here the address b is pointing to remains constant while pt gets shifted by one.

  • The second part is clearly wrong. It **does** yield the offset in the array. –  Apr 29 '13 at 16:49
  • @Guillemo No, the **actual array index,** and not the byte offset, as you think. [Read this.](http://stackoverflow.com/questions/3238482/pointer-subtraction-confusion) –  Apr 29 '13 at 16:53
  • OK, I stand corrected. But just out of curiosity, any way to shift a pointer by bytes rather than by type size? I'm thinking maybe some casting could do the trick, but that code would be nasty. – Guillermo René Ramírez Apr 29 '13 at 17:06
  • I don't think you can do that without invoking UB. –  Apr 29 '13 at 17:07