c – 动态数组分配

前端之家收集整理的这篇文章主要介绍了c – 动态数组分配前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道为什么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.

我对此的理解是,在分配数组时,将选择新的[]表单.你的例子唯一改变的是语法;它不会使语言将数组视为非数组(常规对象).

原文链接:https://www.f2er.com/c/119267.html

猜你在找的C&C++相关文章