您可以使用访问结构变量的成员。(点运算符)在变量名和成员名之间。
例如,要将值赋给s1 struct变量的age成员,请使用如下语句:
s1.age = 19;
也可以将一个结构指定给同一类型的另一个结构:
struct student s1 = {19, 9, "Jason"};
struct student s2;
//....
s2 = s1;
下面的代码演示如何使用结构:
#include <stdio.h>
#include <string.h>
struct course {
int id;
char title[40];
float hours;
};
int main() {
struct course cs1 = {341279, "C++入门", 12.5};
struct course cs2;
/* 初始化cs2 */
cs2.id = 341281;
strcpy(cs2.title, "高级C++");
cs2.hours = 14.25;
/* 显示课程信息 */
printf("%d\t%s\t%4.2f\n", cs1.id, cs1.title, cs1.hours);
printf("%d\t%s\t%4.2f\n", cs2.id, cs2.title, cs2.hours);
return 0;
}
字符串复制需要String.h库中的strcpy()。
还要注意格式说明符%4.2f包括宽度和精度选项。