Search code examples
arraysc

How are array bounds ordered in C?


Suppose I have a 2d array like so:

int arr[4][5];

is this the equivalent of an array of 5 elements where each element is an array with 4 elements, or the other way around? How would indexing work as well?

arr[4][3]; // is this the valid way of getting the most last element?
arr[3][4]; // or this?

I don't know how to properly test which one is correct, because I think C just allows going out of bounds anyway.


Solution

  • A declaration in C gives a “picture” of how a variable will be used.1 So int arr[4][5]; says arr[i][j] will be an int.

    In order for arr[i][j] to be an int, arr[i] must be an array of int, and so arr must be an array of arrays of int.

    The array size expressions break the picture metaphor a little; we will never use arr[4] of an array declared as arr[4]; we will only use indices 0 to 3. However, the size does goes with the index: A declaration of int arr[4][5] associated with a use of arr[i][j] also associates the 4 bound with i and the 5 bound with j.

    So arr[3][4] is the last element, and arr is an array of 4 arrays of 5 int.

    Bonus

    I think C just allows going out of bounds anyway.

    Yes, the C standard “allows” going out of bounds in that it does not stop you from writing expressions that use array elements beyond the bounds of the array. But the standard does not define what happens when a program does that. The C standard is not a walled garden that you cannot leave. It is an open town with defined services in town and no guarantees about what is outside of town, but you are free to come and go.

    Footnote

    1 Kernighan and Ritchie, The C Programming Language, 1978, page 90.