加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么Array * new Array? C失败

发布时间:2020-12-16 03:35:53 所属栏目:百科 来源:网络整理
导读:这个问题在这里已经有一个答案: Using new with fixed length array typedef4个 Is it possible to dynamically create an array of constant size in C++?4个 我一直以为T * p = new T;对于所有T都有效C,直到我尝试 int main(){ typedef int Array[2]; Arr
这个问题在这里已经有一个答案:> Using new with fixed length array typedef4个
> Is it possible to dynamically create an array of constant size in C++?4个
我一直以为T * p = new T;对于所有T都有效C,直到我尝试
int main()
{
    typedef int Array[2];
    Array *p = new Array;
}

并得到这个可爱的错误我无法解密:

error C2440: 'initializing' : cannot convert from 'int *' to 'Array (*)'

有人可以解释为什么这是一个错误?

解决方法

如果您动态分配数组类型,则可以获得指向其第一个元素的指针.

§5.3.4 [expr.new] Entities created by a new-expression have dynamic storage duration. If the entity is a non-
array object,[…]. If it is an array,the new-expression returns a pointer to the initial element of the array.

所以,因为你分配一个数组类型的对象,你得到一个int *:

int *p = new Array;

这与使用typedef没有什么不同:

int *p = new int[2];

这也不符合你的T * p = new T;规则.也就是说,你绝对不能这样做:

int (*p)[2] = new int[2];

我意识到这种混乱可能是由于新的… []作为一种特殊类型的表达与新的…不同而引起的,其中新数组适用于后一种情况.我们经常提出可能会说“new []应该总是匹配delete []”.那条规则有点误导.这里真正意义的是,数组类型的new应该始终与delete []匹配.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读