指向数组的c / c ++指针和指向指针的指针 [英] c/c++ pointer to an array vs pointer to a pointer

查看:157
本文介绍了指向数组的c / c ++指针和指向指针的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为数组和指针基本上是一样的,直到我运行这个程序:

  int main(){
int * a = new int(19);
int b [1];
b [0] = 19;

printf(* a:%d \\\
a:%p \\\
& a:%p \\\
,* a,a,& a);
printf(* b:%d \\\
b:%p \\\
& b:%p \\\
,* b,b,& b);
delete a;
}

输出为:

  * a:19 
a:0x7f94524000e0
& a:0x7fff51b71ab8
* b:19
b:0x7fff51b71ab4
& b:0x7fff51b71ab4

有人可以解释为什么& b的输出与b相同? / p>

谢谢!
-Erben

解决方案

数组和指针是不一样的。指针可以像一个数组(例如通过索引访问)。



& b 是指向整个数组的指针, b 是指向第一个元素的指针。他们可能指向内存中的同一个地址,但它们完全不同。

  + --------- ---------------------- + 
| + ----- + ----- + ----- + --- - + ----- + |
|| | | | | ||
& b ----> || 0 | 1 | 2 | ... | N ||
|| | | | | ||
| + ----- + ----- + ----- + ----- + ----- + |
+ --- ^ --------------------------- +
|
b


I thought array and pointer are basically the same thing, until I run this program:

int main() {
  int* a = new int(19);
  int b[1];
  b[0] = 19;

  printf("*a: %d\n a: %p\n &a:%p\n", *a, a, &a);
  printf("*b: %d\n b: %p\n &b:%p\n", *b, b, &b);
  delete a;
}

output is:

*a: 19
 a: 0x7f94524000e0
 &a:0x7fff51b71ab8
*b: 19
 b: 0x7fff51b71ab4
 &b:0x7fff51b71ab4

can someone please explain why the output of &b is the same as b?

Thanks! -Erben

解决方案

Arrays and pointers are not the same. A pointer can behave like an array (e.g. accessing by index).

&b is a pointer to the whole array and b is a pointer to the first element. They may point to a same address in memory but they are totally different things.

        +-------------------------------+  
        |+-----+-----+-----+-----+-----+|  
        ||     |     |     |     |     ||  
 &b---->||  0  |  1  |  2  | ... |  N  ||  
        ||     |     |     |     |     ||  
        |+-----+-----+-----+-----+-----+|  
        +---^---------------------------+  
            |                              
            b                              

这篇关于指向数组的c / c ++指针和指向指针的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆