C& C ++:指向数组的指针和指向数组的地址有什么区别?

编程入门 行业动态 更新时间:2024-10-27 08:24:57
本文介绍了C& C ++:指向数组的指针和指向数组的地址有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

C ++ 11代码:

C++11 code:

int a[3]; auto b = a; // b is of type int* auto c = &a; // c is of type int(*)[1]

C代码:

int a[3]; int *b = a; int (*c)[3] = &a;

b和c的值相同.

b和c有什么区别?为什么它们不是同一类型?

What is the difference between b and c? Why are they not the same type?

更新:我将数组大小从1更改为3.

推荐答案

sizeof运算符的行为应有所不同,特别是如果将a的声明更改为不同数量的整数,例如:

The sizeof operator should behave differently, for one, especially if you change the declaration of a to a different number of integers, such as int a[7]:

int main() { int a[7]; auto b = a; auto c = &a; std::cout << sizeof(*b) << std::endl; // outputs sizeof(int) std::cout << sizeof(*c) << std::endl; // outputs sizeof(int[7]) return 0; }

对我来说,它打印:

4 28

那是因为两个指针是非常不同的类型.一个是指向整数的指针,另一个是指向由7个整数组成的数组的指针.

That's because the two pointers are very different types. One is a pointer to integer, and the other is a pointer to an array of 7 integers.

第二个确实具有指针数组类型.如果您取消引用它,可以肯定,它在大多数情况下会衰减到指针,但这是实际上不是指向int的指针.第一个是指向int的指针,因为衰减是在赋值时发生的.

The second one really does have pointer-to-array type. If you dereference it, sure, it'll decay to a pointer in most cases, but it's not actually a pointer to pointer to int. The first one is pointer-to-int because the decay happened at the assignment.

其他可能出现的地方是,如果您确实有两个指针数组类型的变量,并试图将一个分配给另一个:

Other places it would show up is if you really did have two variables of pointer-to-array type, and tried to assign one to the other:

int main() { int a[7]; int b[9]; auto aa = &a; auto bb = &b; aa = bb; return 0; }

这为我赢得了错误消息:

This earns me the error message:

xx.cpp: In function ‘int main()’: xx.cpp:14:8: error: cannot convert ‘int (*)[9]’ to ‘int (*)[7]’ in assignment aa = bb;

但是,此示例有效,因为取消引用bb允许它衰减为指向int的指针:

This example, however, works, because dereferencing bb allows it to decay to pointer-to-int:

int main() { int a; int b[9]; auto aa = &a; auto bb = &b; aa = *bb; return 0; }

请注意,衰减不会发生在作业的左侧.这不起作用:

Note that the decay doesn't happen on the left side of an assignment. This doesn't work:

int main() { int a[7]; int b[9]; auto aa = &a; auto bb = &b; *aa = *bb; return 0; }

它为您赢得:

xx2.cpp: In function ‘int main()’: xx2.cpp:14:9: error: incompatible types in assignment of ‘int [9]’ to ‘int [7]’ *aa = *bb;

更多推荐

C&amp; C ++:指向数组的指针和指向数组的地址有什么区别?

本文发布于:2023-07-28 14:04:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1231604.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   指针   有什么区别   地址   amp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!