Bulat M. Bulat M. - 2 months ago 9
C Question

difference between int a[9] and a[3][3]

What is the difference between

#include <stdio.h>

int a[9];

int
main()
{
printf("%d\n", a[1]);
}


and

#include <stdio.h>

int a[3][3];

int
main()
{
printf("%d\n", a[1]);
}


I think both result in placing same 36 byte memory buffer in
.bss
section, what is the difference? Or is
a[3][3]
syntactic sugar over
a[9] - a[3*3]
?

AnT AnT
Answer

int a[3][3] is a semantic sugar of sorts over int a[9]. The raw memory layout it the same (i.e. it is a block of 9 ints), but the language-level access syntax is different. When accessing a[3][3] as a[i][j], the apparent 2D-indexing is converted by the compiler to 1D indexing using i * 3 + j formula.

Comments