【发布时间】:2015-08-07 09:24:26
【问题描述】:
我为一个项目编写了以下代码,但是它未能通过单一测试,要求两个变量不是全局变量,而是main() 的本地变量。修改structexample1.c,使变量student 和anotherStudent 不是全局变量而是main 的局部变量。我对本地和全局概念有模糊的了解,但我不确定如何在我编写的代码中实现问题的要求。
#include <stdio.h>
#include <stdlib.h>
struct student_s {
char* name;
int age;
double height;
struct student_s* next;
} student;
struct student_s anotherStudent;
void printOneStudent(struct student_s student)
{
printf("%s (%d) %s %s %.2lf %s\n", student.name, student.age, ",", "height", student.height, " m");
}
void printStudents(const struct student_s* student)
{
while (student != NULL) {
printOneStudent(*student);
student = student->next;
}
}
int main(void)
{
student.name = "Agnes McGurkinshaw";
student.age = 97;
student.height = 1.64;
student.next = &anotherStudent;
anotherStudent.name = "Jingwu Xiao";
anotherStudent.age = 21;
anotherStudent.height = 1.83;
anotherStudent.next = NULL;
printStudents(&student);
return EXIT_SUCCESS;
}
我知道我需要在main() 中定义这些变量,但我不确定如何以不会完全破坏我的代码的方式实现它们。代码的输出应该保持如下:
Agnes McGurkinshaw (97), height 1.64 m
Jingwu Xiao (21), height 1.83 m
【问题讨论】:
-
为什么不在
main()创建学生,然后再使用呢?