在for循环中填充二维数组

时间:2016-05-05 19:21:58

标签: c arrays for-loop

我想在for循环中填充二维数组。但是,这不起作用。我不知道为什么......

int main () {

int a = 32;
int x = 100;
int y = 1;
int z = 2;
int i, j;

int ar[32][2] = {{1,x},{}};
// works until here!

// gives me that
1   100
0   0
0   0
0   0
...


// I need the array filled
1              100
somenumber     somenumber
somenumber     somenumber
somenumber     somenumber
...

for (i = 1; i <= a; i++) {
    x = (x + y) * z;
    ar[i][i] = {{i + 1, x},{}};
}

return 0;
}
  

test.c:在函数'main'中:   test.c:27:14:错误:'{'标记之前的预期表达式   ar [i] [i] = {{i + 1,x},{}};

为什么它没有填充数组?!

2 个答案:

答案 0 :(得分:1)

谁向你解释说使用[x][y]只是为了创建一个新数组,这种方法并不准确。或者你不明白。您创建一个数组并以这种方式指定其大小ElementType ArrayName[RowSize][ColumnSize];指向。

现在我们创建了2D矩阵。要访问其中的每个元素,我们使用[][]这种表示法,以及我们想要的元素所需的“坐标”,x和y:

ArrayName[1][1] = 1;这会将值1分配给 second 行的第二个中的元素。请注意,如果您提供“超出范围”x或y,系统将崩溃,这是在您将数组创建为RowSizeColumnSize时提供的。

查看您的案例修复:

for(int x = 0; x < YourArray.size(); x++)
{
    for(int y = 0; y < YourArray[i].size(); y++)
    {
         YourArray[x][y] = 1; // this will assign 1 to "all" and "every" element.
         // so if you need to fill you array with something, 
         // here is the place where you are iterating every element in your 2d matrix.
         // using two for loops, outer is for the rows and inner is for the columns
    }
}

答案 1 :(得分:0)

它应该是什么意思?

ar[i][i] = {{i + 1, x},{}};

ar [i] [i]是整数。所以{{i + 1, x},{}}是什么?整数表达? C中没有这样的表达。

更不用说ar是32 * 2数组,所以第一个索引,而我从1运行到32.当i&gt; = 2时,第二个索引是错误的,当i = 32时,第一个索引是错误的太

相关问题