我正在尝试弄清楚 C++ 中数组和指针之间的关系究竟是如何工作的。我已经阅读了很多线程,但我觉得它好像没有粘住。在这里查看这段简短的代码:
int studentAge[5];
int *p = &studentAge[0];
我读到引用运算符 (&) 为数组-> 指针衰减规则创建了一个异常(exception)。因此,从我读到的内容来看,我相信他们是在说 &studentAge
在技术上是指向 5 个整数值的指针,而不是指向单个整数的指针。再详细一点,是不是说它的类型是int(*)[5]
,不能转换成int*
?
如果它是一个指向 5 个整数值的指针,那么这是否意味着它确实退化为一个指针?还是我的想法完全错误?
此外,通过这行代码:
p = studentAge;
如果没有引用运算符,studentAge 数组现在会衰减为指针吗?如果我对此感到困惑,我深表歉意,但正如我之前所说,我很难 100% 清楚这一点。
最佳答案
如果你将一个数组参数传递给一个函数,它确实会衰减为一个指针。如果您引用一个数组,它就不会。
#include <iostream>
void take_array(int arr[]) { // same as (int *arr)
// prints sizeof int*
std::cout << "take_array: " << sizeof arr << '\n';
++arr; // this works, you can increment a pointer
}
void take_array_ref(int (&arr)[10]) { // a reference to an array of int[10]
// prints (sizeof int) * 10
std::cout << "take_array_ref: " << sizeof arr << '\n';
//++arr; // this fails to compile. you can't increment an array
}
int main() {
int arr[10]; // sizeof arr == (sizeof int) * 10
take_array(arr); // decays
take_array_ref(arr); // doesn't decay
int arr2[2];
take_array(arr2); // compiles because it decays
//take_array_ref(arr2); // doesn't compile, type mismatch
}
请注意,第一个签名也可以是 void take_array(int arr[1000]);
或任何其他值,它仍然与具有指针相同;输出仍然是相同的,arr
参数仍然是有效的 int *
关于C++:数组到指针衰减问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25352206/