Can I initialize an empty 2-dimentional C string like this?
int function(void){
char s[50][50]={{}};
}
I'm not sure if string s will be initialized as empty when it's defined in a function like this.
No, you may not, if you want your code to be portable C:
% gcc -pedantic-errors -c init.c
init.c: In function ‘function’:
init.c:2:19: error: ISO C forbids empty initializer braces [-Wpedantic]
char s[50][50]={{}};
^
It is a GCC extension. However you can add a single zero in the braces:
char s[50][50] = {{0}};
or even within just one set of braces:
char s[50][50] = {0};
it will find the first scalar element and initialize it with the given value, and rest of the elements not explicitly initialized will be initialized as if they had a zero initializer. (Note: you could use say 42 for the one element, and rest of them would be still initialized to zero).
Or, since these are arrays of char
, you can use a string in braces:
char s[50][50] = {""};
This will initialize s[0]
with the empty string.
The empty initializer ({ }
) of GCC is needed for another extension - initialization of zero-length flexible array members. It does not exist just to be a generic shorthand.
Standard C does not support initialization of flexible array members, nor does it support arrays of length zero.