[英]initializing multidimensional array in C
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}}; 好的,所以我不能做类似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 我知道这是不理想的,但是我用#ifs这样的代码移交给了我
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. 并被要求摆脱#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. 您说的是一个循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.