我想知道为什么new好像不保留数组信息,只返回一个int*:
#include <iostream>
using namespace std;
typedef int (*p_to_array)[80];
typedef int arr[80];
int main()
{
arr a;
p_to_array p = &a; //fine
p_to_array p2 = new arr; // incompatible types
return 0;
}
最佳答案
我可能完全错了:(即这只不过是一个有根据的猜测)
new arr;
相当于:
new int[80];
根据语言规则返回 int*
。
来自 cppreference.com:(感谢 @interjay 指出我实际上引用了不相关的部分)
The new-expression returns a prvalue pointer to the constructed object or, if an array of objects was constructed, a pointer to the initial element of the array.
我的理解是,在分配数组时,将选择 new[]
形式。您的示例唯一改变的是语法;它不会使语言将数组视为非数组(常规对象)。
关于c++ - 动态数组分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27901367/