I have the following:
#include <stdio.h>
int main() {
int a[2][2] = { 0,1,2,3};
printf("\n%d %d \n%d %d\n",a[0][0],a[0][1],a[1][0],a[1][1]);
printf("%d %d %d %d\n",*a[0],*a[1],*a[2],*a[3]);
return 0;
}
which returns:
0 1
2 3
0 2 0 1491303602
Is there a way to access the 2d array with 1 index? Since the array is held in contiguous memory, shouldn’t we be able to do this?
also:
printf("\n%d %d \n%d %d\n",&a[0][0],&a[0][1],&a[1][0],&a[1][1]);
printf("%d %d %d %d\n",a[0],a[1],a[2],a[3]);
produces the following:
1137924528 1137924532
1137924536 1137924540
1137924528 1137924536 1137924544 1137924552
so why are the memory addresses of the first two elements &a[0][0] = a[0]
and &a[0][1] = a[1] but the last two don’t match?
>Solution :
#include <stdio.h>
int main(void) {
int a[2][2] = { 0,1,2,3};
printf("\n%d %d %d %d\n",a[0][0],a[0][1],a[1][0],a[1][1]);
printf("%d %d %d %d\n",*a[0],*(a[0] + 1), *a[1], *(a[1] + 1));
}
https://godbolt.org/z/3avvnssn5
Result:
0 1 2 3
0 1 2 3