采用恒时长度的char []和新的char []的区别 [英] Difference between char[] and new char[] when using constant lengths

查看:153
本文介绍了采用恒时长度的char []和新的char []的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,这似乎是一个广泛的问题回答,但我更感兴趣的是什么,两者之间究竟发生不同的内部结构。

So this may seem like a widely-answered question, but I'm interested more in the internals of what exactly happens differently between the two.

其他比第二个例子不仅创造了记忆,而是一个指向内存的事实,会发生什么情况的内存的,当出现以下情况:

Other than the fact that the second example creates not only the memory, but a pointer to the memory, what happens in memory when the following happens:

char a[5];
char b* = new char[5];

和更直接的关系的为什么的我问这个问题,为什么我能做到

And more directly related to why I asked this question, how come I can do

const int len = 5;
char* c = new char[len];

而不是

const int len = 5;
char d[len]; // Compiler error

修改应该提到我的VC获得此编译器错误++(去图...)

EDIT Should have mentioned I'm getting this compiler error on VC++ (go figure...)

1>.\input.cpp(138) : error C2057: expected constant expression
1>.\input.cpp(138) : error C2466: cannot allocate an array of constant size 0
1>.\input.cpp(138) : error C2133: 'd' : unknown size

编辑2 :如果已经发布的确切code口与合作。当动态分配的数组常量长度与运行时间值计算产生这个错误。

EDIT 2: Should have posted the exact code I was working with. This error is produced when the constant length for the dynamically allocated array is calculated with run-time values.

假设随机的(A,B)返回 INT 之间的 A b

const int len1 = random(1,5);
char a[len1]; // Errors, since the value
              // is not known at compile time (thanks to answers)

,而

const int len2 = 5;
char b[len2]; // Compiles just fine


推荐答案

不同的是该阵列的寿命。如果你写的:

The difference is the lifetime of the array. If you write:

char a[5];

则数组有它的定义块一生(如果它是
在块范围内定义),其中包含它(如果它的类对象
在类范围内)或静态寿命(定义,如果它在命名空间的定义
范围)。如果你写的:

then the array has a lifetime of the block it's defined in (if it's defined in block scope), of the class object which contains it (if it's defined in class scope) or static lifetime (if it's defined at namespace scope). If you write:

char* b = new char[5];

,则该数组有你关心给它&MDASH的寿命;您必须
明确地终止其生命周期:

, then the array has any lifetime you care to give it—you must explicitly terminate its lifetime with:

delete [] b;

和与问候你的最后一个问题:

And with regards to your last question:

int const len = 5;
char d[len];

是完全合法的,应该编译。那里有一个区别:

is perfectly legal, and should compile. Where there is a difference:

int len = 5;    //  _not_ const
char d[len];    //  illegal
char* e = new char[len];    //  legal

的原因的差异主要是编译技术之一,并
历史:在很早以前,编译器必须知道在长度
为了创建数组作为一个局部变量。

The reason for the difference is mostly one of compiler technology and history: in the very early days, the compiler had to know the length in order to create the array as a local variable.

这篇关于采用恒时长度的char []和新的char []的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆