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.
Use the following declaration instead:
int array[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
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;
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.