Reputation: 13
As you can check this code:
#include<stdio.h>
int main(){
int a[3][4];
int i;
for(i=0;i<12;i++){
a[0][i]=12-i;
printf("a[0][%i] = %i\n", i, a[0][i]);
}
return 0;
}
It properly prints number from 12 to 1. However this piece of code:
#include<stdio.h>
int main(){
int a[3][4];
int i;
for(i=0;i<12;i++){
a[i][0]=12-i;
printf("a[%i][0] = %i\n", i, a[i][0]);
}
return 0;
}
It prints 12, 11, 10, 1, 2, 1. What may be the problem? I know you can print it by using 2 loops and variables, but I am trying to learn how to do it this way.
Upvotes: 1
Views: 279
Reputation: 2857
+---------------------------------------------------------------------------------+
| a[0][0] <--a[0][1] <--a[0][0] |
| a[0][1] <--a[0][2] |
| a[0][2] <--a[0][3] |
| a[0][3] . |
| a[1][0] . <--a[1][0] |
| a[1][1] . |
| a[1][2] . |
| a[1][3] . |
| a[2][0] . <--a[2][0] |
| a[2][1] . |
| a[2][2] <--a[0][10] |
| a[2][3] <--a[0][11] |
| ^ ^ <--a[3][0] <-- already memory overflow ! |
| | | . |
| array memory Y 1th code . |
| others all memory overflow! |
| |
| you 2th code |
+---------------------------------------------------------------------------------+
So, you can usea[i/4][i%4]
just make sure no memory overflow .
Let me say : of course you first code is right , I don't think it is luck.In C , a two dimensional array is always just put two one dimensional togather. However, see my downvote, It is not good to use that.
If you really need speed, you don't want the /
and '%' I think you still can use cide 1th.
Upvotes: -1
Reputation: 6005
It has to do with the way the data are stored in memory. In first case, you add them sequentially, and it has space for 3*4 = 12 elements. So you can luckily put all the elements inside, as you totally have 3*4 cells. On the second case, you are trying to put the data only on each row's first cell, but you have not indicated a space of 12, having indicated 3 rows. For more on memory in multi-dimensional arrays, look here:
How are multi-dimensional arrays formatted in memory?
Upvotes: 0
Reputation: 13177
What you are doing there is bad practice in both cases. You are just lucky that the first way works (because the 3 sub arrays of size 4 are consecutive in memory).
If you want to work with two-dimensional arrays in a one-dimensional loop, you should use the two ways of integer division: /
and %
:
int main(){
int a[3][4];
int i;
for(i=0;i<12;i++){
a[i/4][i%4]=12-i;
printf("a[%i][%i] = %i\n", i/4, i%4, a[i/4][i%4]);
}
return 0;
}
For instance, for i = 7
, we have i/4 == 1
('divide and round down to whole number') and i%4 == 3
('remainder after division').
Upvotes: 3