How does C know the bounds of a multi-dimensional array

arrayc

Coming from Python, if C does not have array bounds, how does it know where a[1] starts?

int a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
b = a[1][1];

Best Answer

C knows the bound of an array at compile time, as opposed to Python which knows the bound of an array at runtime.

The compiler basically rewrite array access into pointer operations. It knows at compile time that the size of a the first dimension of the array is int[3], i.e. sizeof(int)*3. So:

b = a[x][y];

Is basically rewritten to

b = *(a + x * 3 + y);

So the knowledge about the dimension (the number 3) is encoded into the code, even if the dimensions are not explicitly available at runtime. Arguably, arrays are purely a compile-time construct in C.

Related Topic