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

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

C++11 代码:

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 的值是一样的.

The values of b and c are the same.

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

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

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

推荐答案

sizeof 运算符的行为应该有所不同,其中之一,尤其是当您将 a 的声明更改为不同数量的整数,例如 int a[7]:

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; }

这让我收到错误消息:

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

发布评论

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

>www.elefans.com

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