将变量从全局更改为局部-C [英] Changing a variable from global to local - C
问题描述
我已经为一个项目编写了以下代码,但是它未通过单个测试,要求两个变量不是全局变量,而是在main()
中是局部变量.修改structexample1.c
,以使变量student
和anotherStudent
不是全局变量,而是局部变量.我含糊地理解了本地和全球概念,但是我不确定如何在我编写的代码中实现问题所在.
I have written the following code for a project however it fails a singular test asking for two variables to not be global, and instead be local to main()
. Modify structexample1.c
so that the variables student
and anotherStudent
are not global but are local to main. I vaguely understand the local and global concept but I am unsure how to implement what the question is asking into the code I have written.
#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()
中定义这些变量,但是我不确定如何以不完全破坏我的代码的方式来实现它们.代码的输出应保持如下:
I know I will need to define these variables inside main()
but I am unsure how to implement them in a way that does not entirely break my code. The output of the code should remain as follows:
Agnes McGurkinshaw (97), height 1.64 m
Jingwu Xiao (21), height 1.83 m
推荐答案
好吧,首先替换为:
struct student_s {
char* name;
int age;
double height;
struct student_s* next;
} student;
使用:
struct student_s {
char* name;
int age;
double height;
struct student_s* next;
};
(也就是说,删除最后一行中的student
).
(That is, remove student
in the last line).
此更改是必需的,因为您想要定义结构类型,以便以后可以定义类型为struct student_s
的变量,但是您不想在此处定义student
变量,因为那样会使它成为全局变量.
This change is necessary because you want to define the structure type so that you can later define variables of type struct student_s
, but you don't want to define the student
variable here, as that would make it global.
然后删除此行:
struct student_s anotherStudent;
最后,在使用它们之前,先在main()
中声明这两个变量:
And finally, declare both variables in main()
before using them:
int main(void)
{
struct student_s student;
struct student_s anotherStudent;
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;
}
这篇关于将变量从全局更改为局部-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!