[c++] how to initialize a char array?

char * msg = new char[65546];

want to initialize to 0 for all of them. what is the best way to do this in C++?

This question is related to c++ visual-c++

The answer is


what is the best way to do this in C++?

Because you asked it this way:

std::string msg(65546, 0); // all characters will be set to 0

Or:

std::vector<char> msg(65546); // all characters will be initialized to 0

If you are working with C functions which accept char* or const char*, then you can do:

some_c_function(&msg[0]);

You can also use the c_str() method on std::string if it accepts const char* or data().

The benefit of this approach is that you can do everything you want to do with a dynamically allocating char buffer but more safely, flexibly, and sometimes even more efficiently (avoiding the need to recompute string length linearly, e.g.). Best of all, you don't have to free the memory allocated manually, as the destructor will do this for you.


The C-like method may not be as attractive as the other solutions to this question, but added here for completeness:

You can initialise with NULLs like this:

char msg[65536] = {0};

Or to use zeros consider the following:

char msg[65536] = {'0' another 65535 of these separated by comma};

But do not try it as not possible, so use memset!

In the second case, add the following after the memset if you want to use msg as a string.

msg[65536 - 1] =  '\0'

Answers to this question also provide further insight.


The "most C++" way to do this would be to use std::fill.

std::fill(msg, msg + 65546, 0);

memset(msg, 0, 65546)

Absent a really good reason to do otherwise, I'd probably use:

std::vector<char> msg(65546, '\0');

This method uses the 'C' memset function, and is very fast (avoids a char-by-char loop).

const uint size = 65546;
char* msg = new char[size];
memset(reinterpret_cast<void*>(msg), 0, size);

You can use a for loop. but don't forget the last char must be a null character !

char * msg = new char[65546];
for(int i=0;i<65545;i++)
{
    msg[i]='0';
}
msg[65545]='\0';