Home > Net >  Can't assign value to a struct field
Can't assign value to a struct field

Time:05-14

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?

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • c
  • Related