1

Why is it necessary to specify the number of elements of a C-array when it is passed as a parameter to a function (10 in the following example)?

void myFun(int arr[][10]) {}

Is it so because the number of elements is needed to determine the address of the cell being accessed?

Matt
  • 22,721
  • 17
  • 71
  • 112
mrk
  • 3,061
  • 1
  • 29
  • 34

3 Answers3

3

Yes. It's because arr[i][j] means ((int *)arr)[i * N + j] if arr is an int [][N]: the pointer-arithmetic requires the length of a row.

ruakh
  • 175,680
  • 26
  • 273
  • 307
1

The compiler needs to have an idea when the next row starts in memory (as a 2D array is just a continuous chunk of memory, one row after the other). The compiler is not psyche!

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
1

It is only necessary if you used static allocation for your array thought. Because the generate code create a continuous memory block for the array, like pointed out ruakh.

However if you use dynamic allocation it is not necessary, you only need to pass pointers.

Regards

grifos
  • 3,321
  • 1
  • 16
  • 14