Confusing declaration and initializer

Viewed 1670

This declaration is very confusing:

char* q {new char[1024]{}}; // q[i] becomes 0 for all

Is this a “pointer to a char array”, or an “array of char pointers”?

I think that new char[1024]{} is initializing a char array of 1024 elements each having a value of 0.

So this is the same as:

char* q = [0,0,....] // until 1024

Correct?

2 Answers
char* q {new char[1024]{}};

is equal to

char* q = new char[1024]{};

which in turn is equal to

char* q = new char[1024] { 0, 0, 0, 0 /* 1020 more zeros */ }

q is a pointer to a char. In other words, it is of type char *.

It is initialised using the expression new char[1024]{} which dynamically allocates an array of char and zero-initialises them. If this fails, an exception will be thrown.

q will point to the first char in the dynamically allocated array. It is not an array.

It is not the same as

char* q = [0,0,....] // until 1024

since that is invalid syntax. It is also not equivalent to

char* q = {0,0,....}; //  1024 zeros in initialiser

since q is a pointer and cannot be initialised to a set of values. It is closer in (net) effect to

char *q = new char[1024];     //  dynamically allocates chars uninitialised here
std::fill(q, q + 1024, '\0');

except that the characters are initialised to zero, rather than being first uninitialised and then overwritten with zeros (and, of course, it is up to the compiler how it initialises the characters).

Related