I have a simple program:
int main(){
    int *p[2];
    p[0] = new int;
    p[1] = new int;
    *p[0] = 10;
    *p[1] = 12;
    delete p[0];
    delete p[1];
}
Compile:
g++ test.cpp -g -fno-stack-protector -o test
Using GDB to debug (break before variable destruction):
(gdb) x p
0x7fffffffdfc0: 0x5556aed0
(gdb) x &p
0x7fffffffdfc0: 0x5556aed0
(gdb) x p+1
0x7fffffffdfc8: 0x5556aef0
(gdb) x &p+1
0x7fffffffdfd0: 0xffffe0d0
So my question is:
p is same with &p?I think p means the start address of array, namely &p[0], while &p stores the address of array. I thought they share no relationship.p equals &p, what defines the behavior for +1,why p+1 is &p[1], but &p+1 is next address after int *p[2].When an identifier of an array type appears in an expression other than sizeof, address-of (&), or initialization of a reference, it's converted to a pointer to the first array element. Therefore, p means &p[0].
For int *p[2] the type of expression &p is int* (*)[2] pointer to array of 2 pointers to int.
p+1 move to next array element (is equivalent &p[0] + 1) with increment sizeof(int*)
&p+1 move to next array. Increment is sizeof(p) or 2 * sizeof(int*).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With