结构体变量的赋值,结构体变量只能在定义时进行整体赋值吗?不能先定义a,然后给a赋值吗?为什么?

main()
{
struct student
{int num;
char name[20];
char sex[6];
int age;
};
struct student a;
a={103,"wei zhiliang","male",29};
}

定义时并不是整体赋值, 而是初始化, 是在编译时完成的, 不是在程序运行时。
运行时 a={103,"wei zhiliang","male",29}; 这样的语句是不合法的。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-02-22
当然不行。 因为在c中,没有这样的赋值方法啊。

定义的时候,是编译器把初始化的值写好的。

而后面的运行中赋的值 。

就如定义 char aa[] = "wei zhiliang";可以,而
aa = "wei zhiliang"; 是不行的。
只能是 strcpy(aa,"wei zhiliang");

如果是在c++中,可以写一操作符重载函数。
第2个回答  2020-06-19

main()
{
struct student
{int num;
char name[20];
char sex[6];
int age;
};
struct student a;
a={103,"wei zhiliang","male",29};
}

上面的方法不行,下面的就可以

struct student a={103,"wei zhiliang","male",29};
}

另外结构体赋值要在函数内赋值。函数外赋值编译阶段无法识别自定义的数据类型导致无法赋值。

第3个回答  2012-02-22
struct student
{
int num;
char name[20];
char sex[6];
int age;
};

void main()
{
struct student a;
a.num = 1;
strcpy(a.name,"tom");
strcpy(a.sex,"male");
a.age = 18;
}
相似回答