Passing a 2D array of structs

The most important thing when passing arrays as function arguments is: You can’t pass an array to/from a function.

Said that, read the following very carefully. (I’ll use int for simplicity, but of course you can use other types, too.)

But you can pass a “pointer to the first element” of an array. Luckily, C does the conversion automatically. Even more, for all but three exceptions (sizeof, _Alignof, & operators), C converts the name of an array automatically to such a pointer. This is often called “the array decays to a pointer to the first element”.

But this decaying is not recursive. So, if you pass a 2D array to a function, it decays to a pointer to a 1D array:

int a[1][2];    // 1 = outer dimension, 2 = inner

when passed to a function

void f(int a[1][2]);

becomes

int (*a)[2]   // pointer to array of inner dimension

Alternatively one can explicitly use pointer syntax

void f(int (*a)[2]);

The type of a is int (*)[2] for all cases. Mind the parentheses! Which syntax you use is basically personal preference. I do prefer the array syntax with all dimensions, because that documents the intention more clearly.

You always have to pass all sizes, except for the outermost dimension. That is just for documentation and not required (see below for an example).

Inside the function, you use normal index-operator:

int t, i;    // index variable for ouTer, Inner
a[t][i];

Note this can be applied to higher dimension arrays. For 1D array, this also applies, actually. Just remove the inner dimension:

int a[1];

decays to

int *a;

(I just used the constants 1 and 2 to number the dimensions; of course you can use the dimensions you want.)


If you want to pass an array with variable length (VLA, _variable length array), you have to pass all but the outermost dimension to the function:

f(int inner, a[][inner]);

But better for checking, etc. is to pass all dimensions:

f(int outer, int inner, a[outer][inner]);

Leave a Comment