How do you initialise a dynamic array in C++?


Question

How do I achieve the dynamic equivalent of this static array initialisation:

char c[2] = {};  // Sets all members to '\0';

In other words, create a dynamic array with all values initialised to the termination character:

char* c = new char[length]; // how do i amend this? 
1
55
1/8/2010 6:10:26 PM

Accepted Answer

char* c = new char[length]();
102
1/8/2010 7:09:35 PM

Two ways:

char *c = new char[length];
std::fill(c, c + length, INITIAL_VALUE);
// just this once, since it's char, you could use memset

Or:

std::vector<char> c(length, INITIAL_VALUE);

In my second way, the default second parameter is 0 already, so in your case it's unnecessary:

std::vector<char> c(length);

[Edit: go vote for Fred's answer, char* c = new char[length]();]


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon