[错误总结] 结构体成员赋值,报错expected '=', ',', ';', 'asm' or '__attribute__' before '.' token



一个人想着一个人 提交于 2020-08-16 17:15:42

如下一段代码:

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

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!