数组和指针
int array[10] = {1,2,3,4,5,6,7,8};
int *ptr = array;
std::cout<<*(ptr+ 2); => O/P = 3
int (*arr_ptr)[10] = &array;
std::cout<<*(*arr_ptr+2); => O/P = 3
这 2 个有什么区别。我知道它们的意思,但如果它们给出相同的结果,为什么我们有 2 个不同的符号?
int array[10] = {1,2,3,4,5,6,7,8};
int *ptr = array;
std::cout<<*(ptr+ 2); => O/P = 3
int (*arr_ptr)[10] = &array;
std::cout<<*(*arr_ptr+2); => O/P = 3
Whats the difference between these 2. I know what they mean, but if they give same result why do we have 2 different notations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
第一种情况是正常情况:
ptr
是指向数组array
第一个元素的指针,并且它是有索引的(使用*(ptr+2)
,它是ptr[2]
的同义词),用于访问该数组的第三个元素。第二种情况是人为的:arr_ptr 是指向 (enitre) 数组 array 的指针。它首先被取消引用(使用
*arr_ptr
)以生成数组本身,然后将其用作二进制+
的参数,这会导致它隐式转换为 ( nameless) 指向其第一个元素的指针,然后以相同的方式*(+2)
对其进行索引并给出相同的结果。使这些隐式转换显式化,你可以写
The first case is the normal case:
ptr
is a pointer to the first element of the arrayarray
, and it is indexed (using*(ptr+2)
, which is a synonym forptr[2]
) to access the third element of that array.The second case is contrived:
arr_ptr
is a pointer to the (enitre) arrayarray
. It is first dereferenced (with*arr_ptr
) to yield the array itself, which is then used as an argument to binary+
, which causes it to get implicitly converted to a (nameless) pointer to its first element, which is then indexed in the same way*(<nameless pointer>+2)
and gives the same result.Making those implicit conversions explicit, you could write
编辑您的问题后,以下是差异:
array
衰减到指针。理想情况下,ptr
可以指向任何int[]
,无论其大小如何arr_ptr
是指向int[10]< 的指针/代码>。这是非常具体的定义,您永远不能将大小不是
。10
的数组分配给 arr_ptrAfter editing your question, following are the differences:
array
gets decayed to the pointer.ptr
is ideally allowed to point to anyint[]
irrespective of its sizearr_ptr
is a pointer to anint[10]
. It's very specific definition and you can never assign an array toarr_ptr
which has size other than10
.使用您理解且适合问题领域的符号。如果您的应用程序有数组,则使用数组表示法。如果您由于某些其他原因必须四处移动指针,那么第二个版本是合适的。
Use the notation that you understand and that fits the problem domain. If your app has an array, then use array notation. If you have to push pointers around for some other reason, then the second version is appropriate.
事实上,它们对于编译器来说并不相同,并且会导致生成不同的汇编语言。
以下是关于差异的一些很好的参考:http://cplusplus.com/forum/articles/10/< /a>
They are not in fact the same to the compiler, and will result in different assembly language being generated.
Here is some good reference on the difference: http://cplusplus.com/forum/articles/10/