Reputation: 12508
I want to fill a two dimensional array within a for loop. However, that does not work. I have no clue why...
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: In function ‘main’: test.c:27:14: error: expected expression before ‘{’ token ar[i][i] = {{i + 1, x},{}};
Why isn't it filling the array?!
Upvotes: 0
Views: 101
Reputation: 9397
Whoever explained to you that using [x][y]
meant just to create a new array is kind of not accurate. Or you didn't understand right. You create an array and specify its size this way ElementType ArrayName[RowSize][ColumnSize];
point.
Now we created our 2D matrix. To access every element in it, we use [][]
this notation, along with the desired "coordinates" of the element we want, the x and the y:
ArrayName[1][1] = 1;
this will assign the value 1
to the element in the second column on the second row. Notice that your system will crash if you provide "out of range" x or y, which were provided when you created the array as RowSize
and ColumnSize
.
Check out your case fix:
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
}
}
Upvotes: 1
Reputation: 6737
What it supposed to mean?
ar[i][i] = {{i + 1, x},{}};
ar[i][i] is integer. So {{i + 1, x},{}}
is what? Integer expression? There are no such expressions in C.
Not to mention that ar is 32*2 array, so the first index, while i runs from 1 to 32. When i>=2, the second index is wrong, and when i=32, the first index is wrong too.
Upvotes: 0