如下一段代码:
#include "stdio.h"
struct str {
int a;
float b;
char c[10];
};
struct str student;
student.a = 4;
int main()
{
return 0;
}
执行之后会报错, Error expected '=', ',', ';', 'asm' or '__attribute__' before '.' token
造成这种情况的原因是,结构体初始化是可执行代码,必须依赖于函数执行,不能在函数外执行。
因此我们可以作如下更改,将结构体赋值放在函数内执行:
#include "stdio.h"
struct str {
int a;
float b;
char c[10];
};
struct str student;
int main()
{
student.a = 4;
return 0;
}
或者在声明结构体的时候同时初始化:
#include "stdio.h"
struct str {
int a;
float b;
char c[10];
};
struct str student = {1, 2, "abcd"};
int main()
{
return 0;
}