Search code examples
carraysinitializationvariable-length-array

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|


Solution

  • 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}
    };