Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to initialize a char array?

Tags:

c++

visual-c++

char * msg = new char[65546]; 

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

like image 642
5YrsLaterDBA Avatar asked Jun 28 '10 17:06

5YrsLaterDBA


People also ask

How is a char array initialized?

Another useful method to initialize a char array is to assign a string value in the declaration statement. The string literal should have fewer characters than the length of the array; otherwise, there will be only part of the string stored and no terminating null character at the end of the buffer.

How do you initialize a char array in C++?

Because arrays of characters are ordinary arrays, they follow the same rules as these. For example, to initialize an array of characters with some predetermined sequence of characters, we can do it just like any other array: char myword[] = { 'H' , 'e' , 'l' , 'l' , 'o' , '\0' };

How do you initialize a char?

In C++, when you initialize character arrays, a trailing '\0' (zero of type char) is appended to the string initializer. You cannot initialize a character array with more initializers than there are array elements. In ISO C, space for the trailing '\0' can be omitted in this type of information.


2 Answers

char * msg = new char[65546](); 

It's known as value-initialisation, and was introduced in C++03. If you happen to find yourself trapped in a previous decade, then you'll need to use std::fill() (or memset() if you want to pretend it's C).

Note that this won't work for any value other than zero. I think C++0x will offer a way to do that, but I'm a bit behind the times so I can't comment on that.

UPDATE: it seems my ruminations on the past and future of the language aren't entirely accurate; see the comments for corrections.

like image 145
Mike Seymour Avatar answered Oct 06 '22 20:10

Mike Seymour


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

std::fill(msg, msg + 65546, 0); 
like image 45
Peter Alexander Avatar answered Oct 06 '22 19:10

Peter Alexander