c++ - 动态数组分配

标签 c++ arrays

我想知道为什么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/

相关文章:

c++ - 如何将 emacs C++ 模式下的代码对齐到 ";"或 ","?

c++链表 - 插入对象

python - 从具有给定索引数组的 3d numpy 数组中删除 numpy 数组元素

php - 根据项目计数修改列跨度

javascript - 访问 jSON 文件中的子树

c++ - 字符串数组的动态分配 C++

c++ - 关于C++内部类的问题

c++ - 使用 lambda 函数对 STL 容器进行排序

c++ - 函数的返回类型将如何影响 C++ 中的程序

c++ - 使用 std::count_if() 遍历多维数组的列?