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'};
coelhudo
  • 4,710
  • 7
  • 38
  • 57
Luna28
  • 527
  • 3
  • 15
  • 2
    I'm not really sure what you're trying to ask. Are you trying to set every member of the mines array to 0, or are you trying to set the 100th member of the 100th element to 0? – alexyorke Jul 17 '12 at 14:06
  • 2
    Initializer lists used in this manner will specifically set values for all included, everything not included will be initialized to 0. – Chad Jul 17 '12 at 14:09

5 Answers5

2

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).

chris
  • 60,560
  • 13
  • 143
  • 205
2

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));
jsist
  • 5,223
  • 3
  • 28
  • 43
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

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.

Kyle Preiksa
  • 516
  • 2
  • 7
  • 23
  • yes exactly, I'm trying to do the same as this question, and using loops will make the program run slower – Luna28 Jul 17 '12 at 14:12
0

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';
qwertz
  • 14,614
  • 10
  • 34
  • 46
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.

Community
  • 1
  • 1
coelhudo
  • 4,710
  • 7
  • 38
  • 57