使用常量长度时,char []和new char []之间的差异 [英] Difference between char[] and new char[] when using constant lengths

查看:324
本文介绍了使用常量长度时,char []和new 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

EDIT VC ++上的错误(go ...)

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

EDIT 2 :正在使用。

假设随机(a,b) a 之间返回 int c>,

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


推荐答案

数组。如果你写:

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];

,那么数组有任何生命周期,你必须
显式终止其生命周期为:

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

delete [] b;

对于您最后一个问题:

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 []和new char []之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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