9

Why can we omit the first dimension of a multidimensional array when we are passing it to a function?

In my programming class, we were told what when passing a multidimensional array to a function we can omit first dimension, for example, a[10][15][20] can be passed as a[][15][20].

Why?

Marco A.
  • 41,192
  • 25
  • 117
  • 233
Mike Egren
  • 195
  • 1
  • 2
  • 6
  • 1
    The accepted answer to [this question](http://stackoverflow.com/questions/7432831/why-cant-i-omit-the-dimensions-altogether-when-initializing-a-multi-dimensional) explains it pretty well. – Ken White Nov 20 '11 at 22:17
  • Think of an n-dimensional array as a simple array with n-1 dimensional elements. Just as you don't pass the size of a 1 dimensional array, you don't pass the size of the first dimension of an n dimensional array. – David Heffernan Nov 20 '11 at 22:19
  • [Why must I provide a dimension when passing a two-dimensional array to a C function?](http://stackoverflow.com/q/21691924/995714) – phuclv Apr 29 '15 at 07:59

2 Answers2

10

Because the array will decay to pointer and to calculate offset to the elements of the array you do not need to know the innermost dimension. Offset to a[i][j][k] is i*nj*nk+j*nk+k (where nj and nk are corresponding dimensions).

Michael Krelin - hacker
  • 122,635
  • 21
  • 184
  • 169
3

You cannot pass arrays to functions. Any function declared as taking an array type is automatically adjusted to take the corresponding pointer type. When you use the name of an array in a function call expression it decays to a pointer to its first element.

These four declarations declare the same function:

void f(int b[10][15][20]);
void f(int (*b)[15][20]);
void f(int b[][15][20]);
void f(int b[100][15][20]);

and, given int a[10][15][20];, these function calls are identical:

f(a);
f(&a[0]);
CB Bailey
  • 648,528
  • 94
  • 608
  • 638