Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand address for array of pointers?

Tags:

c++

pointers

gdb

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:

  1. Why 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.
  2. Then as 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].
like image 991
JiangFeng Avatar asked Dec 24 '20 09:12

JiangFeng


1 Answers

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*).

like image 166
alex_noname Avatar answered Sep 30 '22 16:09

alex_noname