Reputation: 15229
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....
Upvotes: 2
Views: 2005
Reputation: 2567
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] = ' '} };
Upvotes: 0
Reputation: 310980
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 );
//...
}
Upvotes: 1