how to initialize a matrix in C

1.8k views Asked by At

I need to initialize a h x h matrix in C with spaces.

How to properly do it without cycles?

int h = 8;
char arr[h][h] = {{' '}}; // does not work.... 
2

There are 2 answers

1
Vlad from Moscow On BEST ANSWER

These declarations

int h = 8;
char arr[h][h] = {{' '}};

declare a variable length array. Variable length arrays may be declared only within functions (as for example within main) because they shall have automatic storage duration and may not be initialized in declarations.

So you can write for example

#include <string.h>

//...

int main( void )
{
    int h = 8;
    char arr[h][h];

    memset( arr, ' ', h * h );
    //...
}

That is you can apply the standard function memset that sets all characters of the array with the space character ' '.

Even if you have a non-variable length array nevertheless to initialize its all elements with the space character it is better to use the function memset.

#include <string.h>

//...

int main( void )
{
    enum { h = 8 };
    char arr[h][h];

    memset( arr, ' ', h * h );
    //...
}
11
Krishna Kanth Yenumula On

From GNU site:

To initialize a range of elements to the same value, write ‘[first ... last] = value’. This is a GNU extension

You can use designated initializers. But this type of initialization works, only for constant number of rows and columns.

char arr[8][8] = { { [0 ... 7] = ' '}, { [0 ... 7] = ' '}, { [0 ... 7] = ' '}, { [0 ... 7] = ' '}, { [0 ... 7] = ' '}, { [0 ... 7] = ' '}, { [0 ... 7] = ' '}, { [0 ... 7] = ' '}  };