Difference between char[] and new char[] when usin

2019-04-01 06:56发布

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

but not

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

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: 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.

Assuming random(a,b) returns an int between a and b,

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

whereas

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

8条回答
聊天终结者
2楼-- · 2019-04-01 07:28

In C++ you can't have dynamic arrays in stack. C99 has this feature, but not C++.

When you declare char d[ len ] you are allocating space on stack. When you do char *c = new char[ len ] you allocate space on heap.

The heap has its manager and can allocate variable amounts of memory. In C++, the stack must be allocated by constant expression values, so the compiler has room for lots of optimizations. The compiler is aware of how much space will be spent on a given context this way and is able to predict stack frames. With dynamic arrays, it wouldn't be possible, so the language staff decided to forbid it (at least until C++11).

查看更多
孤傲高冷的网名
3楼-- · 2019-04-01 07:29

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

, 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.

查看更多
登录 后发表回答