'Can't assign value to a struct field

Why does the following code:

struct number {
    int num1;
    int num2;
} arr[5];

arr[0].num1 = 1;

int main()
{
    return 0;
}

produces:

main.c:8:8: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘attribute’ before ‘.’ token arr[0].num1 = 1;

but if I move line arr[0].num1 = 1; inside the main function, it works without producing the error?

c


Solution 1:[1]

The line

arr[0].num1 = 1;

is a statement, not a declaration.

All statements must be inside a function. It does not make sense to put statements outside a function, because in that case, it is unclear when these statements are supposed to be executed.

If you want to initialize arr[0].num1 outside the function main, then you will have to initialize it as part of the declaration of arr, for example like this:

struct number {
    int num1;
    int num2;
} arr[5] = { {1,0},{0,0},{0,0},{0,0},{0,0} };

Solution 2:[2]

You'd either have to create a function to store the statement or run it in the main() clause

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2