[英]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.