Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a two-dimensional array in C be initialized without explicit size?

I have a question regarding two-dimensional arrays in C. I know now (from direct compiler experience) that I can't initialize such an array analogously to one-dimensional arrays like this:

int multi_array[][] = {
  {1,2,3,4,5},
  {10,20,30,40,50},
  {100,200,300,400,500}
};

> compiler output:

gcc -o arrays arrays.c
arrays.c: In function ‘main’:
arrays.c:8:9: error: array type has incomplete element type

The closest solution that works is to provide the number of columns explicitly like this:

int multi_array[][5] = {
  {1,2,3,4,5},
  {10,20,30,40,50},
  {100,200,300,400,500}
};

My question is: can it be done neatly without supplying the number explicitly (which after all the compiler should be able to infer itself)? I'm not talking about manually constructing it with malloc or something but rather something close to what I tried. Also, can someone knowledgeable about C compilers explain from a low-level perspective why my initial attempt does not work?

I used plain gcc with no non-standard options to compile the code.

Thanks

like image 574
Wojciech Gac Avatar asked Feb 28 '14 16:02

Wojciech Gac


People also ask

How is a two-dimensional array initialized in C?

Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. Ex: int a[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the second row to one. The initialization is done row by row.

Can we declare a 2D array without column?

Note: When you initialize a 2D array, you must always specify the first dimension(no. of rows), but providing the second dimension(no. of columns) may be omitted.


1 Answers

2D arrays in C are stored in contiguous memory locations. So if you do not provide the number of rows or the number of columns, how will the compiler know how many rows and column there are?

For a row major matrix, rows contents are at contiguous memory positions. So you need to specify at least the number of columns. Similarly for a column major matrix, you need to specify at least the number of rows. Whether it is row major or column major is defined by architecture. It seems that what you have is a row major architecture.

like image 119
HelloWorld123456789 Avatar answered Oct 16 '22 03:10

HelloWorld123456789