1

I am trying to initialize a multidimensional array in the following way but I am not sure if it is correct. I am re-initializing large tables implemented using multidimensional arrays and I am not sure how to do it. I need to initialize the entire row at a time and cannot initialize the elments individually.

int array[3][3];
int ind = 0;
array[ind++] = {1,2,3};
array[ind++] = {4,5,6};
array[ind++] = {7,8,9};

Ok so i cannot do something like array[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; because what I actually want to do is something like this

int array[][3];
int ind = 0;
array[ind++] = {1,2,3};
if(contion1)
   array[ind++] = {4,5,6};
else 
   array[ind++] = {0,0,0};
array[ind++] = {7,8,9};

I hope this makes it more clear. This is not ideal, I know but I was handed over the code with #ifs something like this

int array[][3] = {
     {1,2,3},
     #if contion1
        {4,5,6},
     #else 
        {0,0,0},
    {7,8,9}};

and was asked to get rid of the #ifs.

SHuss
  • 41
  • 7
  • 2
    possible duplicate of [Multidimensional array initialization in C](http://stackoverflow.com/questions/18157251/multidimensional-array-initialization-in-c) – Ranic Jul 23 '14 at 13:58
  • What do you mean get rid of the ifs? To what value do you want to set it? – Igor Pejic Jul 23 '14 at 14:20

3 Answers3

3

Use the following declaration instead:

int array[3][3] = {
                   {1, 2, 3},
                   {4, 5, 6},
                   {7, 8, 9}
                  };
Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50
1

To reinitialize you will have to use loops

for ( i = 0; i < 3; i++) {
    condition = // whatever your condition is 
    for ( n =0; n < 3; n++) {
        // if condition is zero your value is 0 non-zero condition gets the calculated value
        array[i][n] = condition ? ( i * 3) + n + 1 : 0;
    }
}
user3121023
  • 8,181
  • 5
  • 18
  • 16
1

So you basically want a loop:

int num = 1;
for(i = 0 ; i < 3 ; i++)
{
    for(j = 0 ; j < 3 ; j++)
    {
        arr[i][j] = num;
        num++;
    }
}

as simple as that. You cannot initialize an array in one line - only in the first declaration. The idea of what you're saying is a loop.

Zach P
  • 1,731
  • 11
  • 16