Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c++ - How to understand address for array of pointers?

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].

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...