0

"When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the array. However, the number of col

"When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the array. However, the number of columns should always be specified" why is that, and why doesn't it work if we specify the number of column rather than rows.

26th Apr 2022, 6:56 PM
blueshipswims
blueshipswims - avatar
1 Answer
+ 5
It has to do with how arrays are stored in memory. C uses "last index runs fastest". That means, a two-dimensional array is stored row by row in a contiguous block of memory . Not every language follows that pattern, incidentally, there are languages that follow first index runs fastest. Since the array is stored row by row, all you need to calculate the correct offset into the k-th row is the number of columns. Then an element a[i][j] can be calculated as *(a + n*i + j), where n is the number of columns per row. How many rows there are is not relevant. C has no protection against accessing out of bounds. An array passed as argument into a function degenerates to a pointer. From that last perspective, one can also argue that, because arrays are stored row-wise, that a two dimensional array is a pointer to an array of some data type. As usual, you can specify this as a pointer, but the type is then "array of something". For example, you can pass a 2-by-3 two-dim array of integers as int(*)[3] type - as pointer to array of 3 integers.
26th Apr 2022, 7:05 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar