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& C ++:指向数组的指针和指向数组的地址有什么区别?
发布评论