Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I initialize a struct in C

I got a comment on how I initialize my struct in C, saying that It does not work and it does not compile either.

This is how I create and initialize a structure in C.

struct {
int a; 
int b;
char arr[3];
.
.
.
} data = {
.a = 1, 
.b = 2
};

main(){
/* do stuff */
}

This how I initialize my struct and It works and compiles. Yet I got a comment saying this would compile for c++ but not for C. Can someone ensure me that this correct alternative? If not why is it compiling with no errors?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think there is a typo in the declaration of the data member arr. Instead of

char [3]arr;

you have to write

char arr[3];

You may not initialize an array with empty braces. So write for example

struct {
int a; 
char arr[3];
.
.
.
} data = {
.a = 1, 
.arr = { 0 }
};

In fact it is enough to write

struct {
int a; 
char arr[3];
.
.
.
} data = {
.a = 1
};

The array implicitly will be initialized with zeroes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading