Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...