Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason C compiler demands that number of columns in a 2d array will be defined?

Tags:

c

given the following function signature:

void readFileData(FILE* fp, double inputMatrix[][], int parameters[])

this doesn't compile.

and the corrected one:

void readFileData(FILE* fp, double inputMatrix[][NUM], int parameters[])

my question is, why does the compiler demands that number of columns will be defined when handling a 2D array in C? Is there a way to pass a 2D array to a function with an unknown dimensions?

thank you

like image 647
Asher Saban Avatar asked Aug 20 '10 14:08

Asher Saban


People also ask

Why do we need to specify column size in 2D array?

When passing a two-dimensional array to a function, you must specify the number of columns as a constant when you write the parameter type, so the compiler can pre-calculate the memory addresses of individual elements. This function computes the total of a given row.

What is the size of 2D array in C?

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a table with 3 rows and each row has 4 columns. Similarly, you can declare a three-dimensional (3d) array.

Is it necessary to include the number of rows when specifying a two-dimensional array argument in a function definition?

Example 2: Passing Multidimensional Array to a Function Note: It is not mandatory to specify the number of rows in the array. However, the number of columns should always be specified.

What is column major in 2D array?

Column Major ordering According to the column major ordering, all the columns of the 2D array are stored into the memory contiguously. The memory allocation of the array which is shown in in the above image is given as follows.


1 Answers

Built-in multi-deminsional arrays in C (and in C++) are implemented using the "index-translation" approach. That means that 2D (3D, 4D etc.) array is laid out in memory as an ordinary 1D array of sufficient size, and the access to the elements of such array is implemented through recalculating the multi-dimensional indices onto a corresponding 1D index. For example, if you define a 2D array of size M x N

double inputMatrix[M][N]

in reality, under the hood the compiler creates an array of size M * N

double inputMatrix_[M * N];

Every time you access the element of your array

inputMatrix[i][j]

the compiler translates it into

inputMatrix_[i * N + j]

As you can see, in order to perform the translation the compiler has to know N, but doesn't really need to know M. This translation formula can easily be generalized for arrays with any number of dimensions. It will involve all sizes of the multi-dimensional array except the first one. This is why every time you declare an array, you are required to specify all sizes except the first one.

like image 181
AnT Avatar answered Oct 24 '22 19:10

AnT