在C语言中,有几种不同的方式来声明和使用结构体:
- 如果使用
struct student作为类型名,那么每次使用时都需要带上struct关键字:
struct student *b; // 必须使用 struct student
2.如果想省略 struct 关键字,可以使用 typedef 来创建新的类型名:
typedef struct student {
long sno;
char name[10];
float score[3];
} Student; // 创建新的类型名 Student// 现在就可以直接使用 Student
Student *b; // 不需要写 struct
原始代码:
#include <stdio.h>
#include <string.h>
struct student {
long sno;
char name[10];
float score[3];
};
void fun(struct student *b) {
b->sno = 10004; // 修改学号,或:(*b).sno = 10004;
strcpy(b->name, "LiJie"); // 修改姓名,或:(*b).name = "LiJie";
// 成绩保持不变,无需修改
}
int main() {
struct student t = {10002, "ZhangQi", {93.00, 85.00, 87.00}};
printf("修改前的数据:\n");
printf("学号:%ld\n姓名:%s\n成绩:%.2f, %.2f, %.2f\n\n",
t.sno, t.name, t.score[0], t.score[1], t.score[2]);
fun(&t); // 调用函数修改数据
printf("修改后的数据:\n");
printf("学号:%ld\n姓名:%s\n成绩:%.2f, %.2f, %.2f\n",
t.sno, t.name, t.score[0], t.score[1], t.score[2]);
return 0;
}
修改后的完整代码可以是:
#include <stdio.h>
#include <string.h>
typedef struct student {
long sno;
char name[10];
float score[3];
} Student; // 创建新的类型名
void fun(Student *b) { // 现在可以省略 struct
b->sno = 10004; // 修改学号,或:(*b).sno = 10004;
strcpy(b->name, "LiJie"); // 修改姓名,或:(*b).name = "LiJie";
}
int main() {
Student t = {10002, "ZhangQi", {93.00, 85.00, 87.00}};
fun(&t);
printf("学号:%ld\n姓名:%s\n成绩:%.2f, %.2f, %.2f\n",
t.sno, t.name, t.score[0], t.score[1], t.score[2]);
return 0;
}
这样修改后,代码看起来更简洁,这也是现代C语言编程中更常用的方式。不过两种方式都是正确的,选择哪种主要取决于编程风格和项目规范。