Search code examples
c++memoryinitializationarraysdynamic-allocation

Difference between char[] and new char[] when using constant lengths


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

Solution

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