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;