ABC
ABC

Reputation: 645

How to initialize an array of structs in C

I can not see why my code doesn't work

#include <stdio.h>
#include <stdlib.h>

typedef struct date{
    int month, day, year;
} Date;

typedef struct person{
    char name[32];
    Date date;
}Person;

int main()
{
    Person presidents[4];
    presidents[0] = {"George Washington", {30, 4, 1789}};
    presidents[1] = {"Thomas Jefferson", {4, 3, 1801}};
    presidents[2] = {"Abraham Lincoln", {4, 3, 1861}};
    presidents[3] = {"Theodore Roosevelt", {14, 8, 1901}};

    return 0;
}

This is the compiler's output:

>||=== Build: Debug in MyProject (compiler: GNU GCC Compiler) ===|
>C:\Users\My pc\OneDrive\Documents\c\MyProject\main.c||In function 'main':|
>C:\Users\My pc\OneDrive\Documents\c\MyProject\main.c|16|error: expected expression before '{' token|
>C:\Users\My pc\OneDrive\Documents\c\MyProject\main.c|17|error: expected expression before '{' token|
>C:\Users\My pc\OneDrive\Documents\c\MyProject\main.c|18|error: expected expression before '{' token|
>C:\Users\My pc\OneDrive\Documents\c\MyProject\main.c|19|error: expected expression before '{' token|
>C:\Users\My pc\OneDrive\Documents\c\MyProject\main.c|15|warning: variable 'presidents' set but not used [-Wunused-but-set-variable]|
>||=== Build failed: 4 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|

Upvotes: 0

Views: 94

Answers (2)

David Ranieri
David Ranieri

Reputation: 41017

As an extension to @RobertoCaboni's answer, since C99 you can also use compound literals:

Person presidents[4];
presidents[0] = (Person){"George Washington", {30, 4, 1789}};
presidents[1] = (Person){"Thomas Jefferson", {4, 3, 1801}};
presidents[2] = (Person){"Abraham Lincoln", {4, 3, 1861}};
presidents[3] = (Person){"Theodore Roosevelt", {14, 8, 1901}};

Upvotes: 2

Roberto Caboni
Roberto Caboni

Reputation: 7490

Try:

Person presidents[] = {
    {"George Washington", {30, 4, 1789}},
    {"Thomas Jefferson", {4, 3, 1801}},
    {"Abraham Lincoln", {4, 3, 1861}},
    {"Theodore Roosevelt", {14, 8, 1901}}
};

The initialization is always in the form

type var = init_val;

and the code above shows how to initalize an array of structs. Please note how you don't need to specify the number of elements of the presidents array, as the compiler will obtain it from the number of elements in the initializer.

Upvotes: 2

Related Questions