[英]Declare struct inside main()
我是C的新手。我被要求修改这个程序,以使变量student
和anotherStudent
不是全局的,但是对main是局部的。它仍将由printStudnets
打印。 不允许使用typedef
。 我知道是否在main中声明struct,并且仅对main函数是必需的。是否必须在每个函数中声明struct才能实现?
#include <stdio.h>
#include <stdlib.h>
struct student_s {
char* name;
int age;
struct student_s* next;
} student;
struct student_s anotherStudent;
void printOneStudent(struct student_s student)
{
printf("%s (%d)\n", student.name, student.age);
}
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.next = &anotherStudent;
anotherStudent.name = "Jingwu Xiao";
anotherStudent.age = 21;
anotherStudent.next = NULL;
printStudents(&student);
return EXIT_SUCCESS;
}
您无需使用typedef
即可定义新的结构化类型。 这是完全正确的:
struct student_s {
char* name;
int age;
struct student_s* next;
}; // Remove "student". Now you don't have a global variable.
结果是, student_s
不是您的结构化类型的名称; 它是您的结构化类型的标记 。 因此,声明对应于student_s
的结构化类型的对象必须以关键字struct
开头:
int main(void)
{
struct student_s student;
... // The rest of your code remains the same
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.