0

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)) ===|

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@BUG you can, using compound literals (as suggested by DavidRanieri), but it would be technically a set of assignments and not an initialization. You cannot do as you did... because the C syntax forbids it.
2

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}};

1 Comment

+1, though it is technically an assignment rather than an initialization. But it is correct as I guess OP meant asking about the assignment in general.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.