The four programs below input a 2 D array and then print it out.
- The first one prints out garbage values and also gives out a few warnings (Which I did not understand).
- The 2nd one works correctly , also it kinda makes sense as I believed that a 2 D array is stored linearly in memory.
- The 3rd one works correctly , but I have no idea why it works.
The 4th one works as well.
So it would be of great help if someone could explain how each of the methods work , cheers
I'm afraid my understanding of how pointers work isn't as good as I thought.
int main(){
int n;
int a [3][4];
int i=0,j=0,count=0;
for(i=0;i<3;i++){
for(j=0;j<4;j++){
scanf("%d",(a+4*i+j)); // Output-514623632 514623648 514623664 514623680 514623696 514623712 514623728 514623744 514623760 514623776 514623792 514623808
}
}
for(i=0;i<3;i++){
for(j=0;j<4;j++){
printf("%d\t",*(a+4*i+j));
}
}
return 0;
}
Warnings -solution.c:15:21: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int (*)[4]’ [-Wformat=]
scanf("%d",(a+4*i+j));
solution.c:20:22: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("%d\t",*(a+4*i+j));
~^ ~~~~~~~~~
%ls
int main(){
int n;
int a [3][4];
int i=0,j=0,count=0;
for(i=0;i<3;i++){
for(j=0;j<4;j++){
scanf("%d",*(a+4*i+j));
}
}
for(i=0;i<3;i++){
for(j=0;j<4;j++){
printf("%d\t",**(a+4*i+j)); // Output -1 2 3 4 5 6 7 8 9 10 11 12
}
}
return 0;
}
int main(){
int n;
int a [3][4];
int i=0,j=0,count=0;
for(i=0;i<3;i++){
for(j=0;j<4;j++){
scanf("%d",(*(a+i)+j));
}
}
for(i=0;i<3;i++){
for(j=0;j<4;j++){
printf("%d\t",*(*(a+i)+j)); // Output- 1 2 3 4 5 6 7 8 9 10 11 12
}
}
return 0;
}
int main(){
int n;
int * a=(int*)malloc(12*sizeof(int)) ;
int i=0,j=0,count=0;
for(i=0;i<3;i++){
for(j=0;j<4;j++){
*(a+4*i+j)=++count;
}
}
for(i=0;i<3;i++){
for(j=0;j<4;j++){
printf("%d\n",*(a+4*i+j)); // Output- 1 2 3 4 5 6 7 8 9 10 11 12
}
}
return 0;
}