Since the question keeps changing, I define:
1: memset( buffer, '\0', sizeof(buffer) );
2a: memset( buffer, '\0', sizeof(char*) * ARRAY_LENGTH );
2b: memset( buffer, '\0', sizeof(char) * ARRAY_LENGTH );
3: memset( buffer, '\0', ARRAY_LENGTH );
If the question is merely, "what is the correct way to call memset
" rather than "what is the best way to zero this array", then either 2b or 3 is correct. 1 and 2a are wrong.
You can have a style war over 2b vs 3: whether to include the sizeof(char)
or not -- some people leave it out because it's redundant (I usually do), other people put it in to create a kind of consistency with the same code setting an array of int
. That is to say they always multiply a size by a number of elements, even though they know the size is 1. One possible conclusion is that the "safest" way to memset the array pointed to by buffer
is:
std::memset(buffer, 0, sizeof(*buffer) * ARRAY_LENGTH);
This code remains correct if the type of buffer changes, provided of course that it continues to have ARRAY_LENGTH
elements of whatever type that is, and provided that all-bits-zero remains the correct initial value.
Another option beloved of "C++ is not C" programmers, is:
/* never mind how buffer is allocated */
std::fill(buffer, buffer + ARRAY_LENGTH, 0);
If you care, you can then check for yourself whether or not your compiler optimizes this to the same code to which it optimizes the equivalent call to std::memset
.
char *buffer = new char [ARRAY_LENGTH]();
is nifty but almost useless in C++ in practice because you pretty much never allocate an array with new
in the first place.
std::string buffer(ARRAY_LENGTH, 0);
introduces a particular way of managing the buffer, which may or may not be what you want but often is. There's a lot to be said for char buffer[ARRAY_LENGTH] = {0};
in some cases.