Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a char array at declaration

Tags:

c

gcc

Are these 2 methods equivalent ?

char a[10] = "";
char a[10] = { 0 };

Also, I would like to declare-initialize a struct but this will not work in gcc:

struct c
{
    char d[10];
    int e; 
};
struct c f = { 0 };

a.c: In function ‘main’:
a.c:33: warning: missing braces around initializer
a.c:33: warning: (near initialization for ‘f.d’)
a.c:33: warning: missing initializer
a.c:33: warning: (near initialization for ‘f.e’)
a.c:33: warning: unused variable ‘f’

like image 505
Neeladri Vishweswaran Avatar asked Aug 16 '26 04:08

Neeladri Vishweswaran


1 Answers

Yes, the two char[] initialisations are identical - both will initialise the array to contain zeros.

For the structure problem, try:

struct c f = { {0}, 0 };

(With newer versions of gcc that support C99 you can also name the elements of the structure being initialised.)

like image 71
psmears Avatar answered Aug 18 '26 18:08

psmears



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!