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.

2
  • 2
    possible duplicate of Multidimensional array initialization in C Commented Jul 23, 2014 at 13:58
  • What do you mean get rid of the ifs? To what value do you want to set it? Commented Jul 23, 2014 at 14:20

3 Answers 3

3

Use the following declaration instead:

int array[3][3] = {
                   {1, 2, 3},
                   {4, 5, 6},
                   {7, 8, 9}
                  };
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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;
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.