srira
srira

Reputation: 61

Difference between 1d and 2d arrays in C

 int arr[3][2]={{1,2},{3,4},{5,6}};
 int *c=&arr;
 for(i=0;i<3;i++)
 {
      for(j=0;j<2;j++)
      {
          printf("\n %d %d",((arr+i)+j),*(*(arr+i)+j));
      }             
 }
 for(i=0;i<6;i++)
 {
      printf("\n%d",(c++));
 }

output:
 2293536 1
 2293536 2
 2293552 3
 2293552 4
 2293568 5
 2293568 6

 2293536
 2293540
 2293544
 2293548
 2293552

I cannot understand this: why one dimensional array is not same as 2d? Both are stored like linear array. arr[1][0] is not same as (arr+0)+1. why address are different in arr?

Upvotes: 1

Views: 2241

Answers (1)

Filipe Gon&#231;alves
Filipe Gon&#231;alves

Reputation: 21213

arr[1][0] is not the same as (arr+0)+1 - it was never supposed to be. arr[1][0] is equivalent to *(*(arr+1)+0), or, if you mean the address, then &arr[1][0] is the same as *(arr+1)+0.

Thus, your printf is wrong:

printf("\n %d %d",((arr+i)+j),*(*(arr+i)+j));

Remember, since arr is a 3 by 2 array, arr+x is 2*sizeof(int) bytes away. Because of that, you are printing addresses that don't match what you dereference. arr+i+j is not the address of *(*(arr+i)+j).

If you want to print the address followed by what is in there, you should use this instead:

printf("\n %p %d", (void *) *(arr+i)+j,*(*(arr+i)+j));

Note the format specifier %p. It must be *(arr+i)+j, and not (arr+i)+j, because *(arr+i) is of type int * - it's a pointer to the first element in arr[i].

Your second printf call:

printf("\n %d %d",(c++));

Is invalid: you specify two format specifiers and provide only one.

Upvotes: 2

Related Questions