I'm writing a program in C++, and I'm trying to declare an array with value but only this value is set only to the first member in the array.
char mines[100][100] = {'0'};
I'm writing a program in C++, and I'm trying to declare an array with value but only this value is set only to the first member in the array.
char mines[100][100] = {'0'};
Use std::fill
on each dimension:
for (int i = 0; i < 100; ++i)
std::fill (mines[i], mines[i] + 100, '0');
Or in C++11:
for (auto &chars : mines)
std::fill (std::begin (chars), std::end (chars), '0');
Even easier, using the fact that arrays are contiguous, you can save yourself the loop:
std::fill (mines, mines + 100*100, '0');
To eliminate the magic number there, as Shahbaz points out, replace mines + 100*100
with sizeof(mines)
.
If you don't want to write or generate an initializer list of 10000 elements, you could do:
char mines[100][100];
memset(mines, '0', sizeof(mines));
I usually use a for loop to initialize all values. As far as I know, you can only initalize by a list, not a default value for all elements.
You will only init the first element by doing
char mines[100][100] = {'0'};
The rest will be initialized with 0
(the value not the character) you will need a loop. Like this:
int row, column;
for (row = 0; row < 100; row++)
for (column = 0; column < 100; column++)
mines[row][column] = '0';
Luna, this is called zero-initializer and only works to initialize all values to zero corresponding value: null pointers, zero. If you try to initialize char to 0 it will work, but with any other value will not.
More information here.
#include <iostream>
int main(int argc, char *argv[])
{
int value[2][2] = {0};
for(int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
std::cout << (value[i][j] == 0) << std::endl;
return 0;
}
Output:
1 1 1 1
If you need to initialize with a specific value, in my opinion Luchian has the best solution with memset.