The users @JoachimPileborg and @GeorgSchölly have already explained in their answers which functions can be used to reinitialize an array. However, I'd like to add some sample code and explain a difference between std::fill()
and memset()
.
I assume that you want to (re)initialize your array with 0. In this case you can do it as shown in the following code:
#include <xutility> // For std::fill().
int main(int argc, char* argv[])
{
const int x = 2;
const int y = 3;
const int z = 5;
const int arraySize = x * y * z;
// Initialize array with 0.
int ID[x][y][z] = {};
// Use the array...
// Either reinitialize array with 0 using std::fill()...
std::fill(&ID[0][0][0], &ID[0][0][0] + arraySize, 0);
// ...or reinitialize array with 0 using memset().
memset(&ID[0][0][0], 0, sizeof(ID));
// Reuse the array...
return 0;
}
However, if you want to initialize your array with another value (for example, 1), then you have to be aware of a crucial difference between std::fill()
and memset()
: The function std::fill()
sets each element of your array to the specified value. The function memset()
, in contrast, sets each byte your array to the specified value. This is why memset()
takes the array size as number of bytes (sizeof(ID)
).
If you initialize your array with 0, this difference doesn't cause a problem.
But, if you want to initialize each element of your array with a non-zero value, then you have to use std::fill()
, because memset()
will yield the wrong result.
Let's assume you want to set all elements of your array to 1, then the following line of code will yield the expected result:
std::fill(&ID[0][0][0], &ID[0][0][0] + arraySize, 1);
However, if you use memset()
in the following way, then you get a different result:
memset(&ID[0][0][0], 1, sizeof(ID));
As explained above, this line of code sets every byte to 1. Therefore, each integer element of your array will be set to 16843009, because this equals the hexadecimal value 0x01010101.