user8965395
user8965395

Reputation:

How to initialize multidimentional array in C Programming

I am getting error when i am running this code

int row1=2,col1=2;

int mat1[row1][col1]=
{
    {1,5},
    {4,6}
};

What is wrong with this code??

IDE: CodeBlocks

error: variable-sized object may not be initialized|

Upvotes: 0

Views: 90

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

As per C specs, an array defined like

int mat1[row1][col1]=
{
    {1,5},
    {4,6}
};

is a VLA (Variable Length Array) and cannot be initialized.

Quoting C11, chapter §6.7.6.2/P4,

[...] If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.

and chapter §6.7.9

The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

You need to use compile time constant expressions as array dimensions to be able to use brace enclosed initializers.

You can use #define MACROs for this, like

#define ROW 2  //compile time constant expression
#define COL 2  //compile time constant expression

int mat1[ROW][COL]=
{
    {1,5},
    {4,6}
};

Upvotes: 2

madbuggerswall
madbuggerswall

Reputation: 101

You are trying to initialize a variable-sized object. You could try assigning the values later somewhere else or simply use numbers instead of variables.

Upvotes: 0

dbush
dbush

Reputation: 223689

What you have here is a variable length array. Such an array cannot be initialized. You can only initialize an array if the dimensions are constants (i.e. numeric constants, not variables declared as const):

int mat1[2][2]=
{
    {1,5},
    {4,6}
};

Upvotes: 5

Related Questions