简体   繁体   English

无法为结构字段赋值

[英]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 '.' main.c:8:8: error: expected '=', ',', ';', 'asm' or ' attribute ' before '.' token arr[0].num1 = 1;令牌 arr[0].num1 = 1;

but if I move line arr[0].num1 = 1;但是如果我移动行arr[0].num1 = 1; inside the main function, it works without producing the error?main function 内部,它可以正常工作而不会产生错误?

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.所有语句都必须在 function 内。将语句放在 function 之外是没有意义的,因为在那种情况下,不清楚这些语句应该在何时执行。

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:如果要在 function main之外初始化arr[0].num1 ,则必须将其初始化为arr声明的一部分,例如:

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

You'd either have to create a function to store the statement or run it in the main() clause您要么必须创建一个 function 来存储该语句,要么在 main() 子句中运行它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM