结构类型定义为:
typedef struct student{
int id;
char* name;
double score;
} Student;
我构造了一个 Student 类型的变量,并且想为其赋值。我怎样才能有效地做到这一点?
int main(){
Student s1;
int id = 3;
char* name = getName(id);
double score = getScore(id);
/*Error
s1 = {id, name, score};
*/
/* Can I avoid assigning values individually?
s1->id = id;
s1->name = name;
s1->score= score;
*/
return 0;
}
在 C99 标准中,您可以使用复合文字赋值:
Student s1;
s1 = (Student){.id = id, .name = name, .score = score};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)