gpt4 book ai didi

将变量从全局更改为局部 - C

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:57 26 4
gpt4 key购买 nike

我已经为一个项目编写了以下代码,但是它未能通过单一测试,要求两个变量不是全局的,而是 main() 的局部变量。修改 structexample1.c,使变量 studentanotherStudent 不是全局的,而是局部于 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

最佳答案

好吧,首先替换这个:

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)。

此更改是必要的,因为您要定义结构类型以便稍后可以定义类型为 struct student_s 的变量,但您不想定义 student 此处为变量,因为这将使它成为全局变量。

然后删除这一行:

struct student_s anotherStudent;

最后,在使用前在 main() 中声明这两个变量:

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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31874189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com