再见,
我在 C 上再次遇到这个问题,但现在使用 struct。 有这样的student结构
struct student {
char *name;
int age;
}
我想要一个列表,我可以在其中添加一些学生,还可以查看其所有元素。这是我到目前为止完成的代码。
#include<stdio.h>
#include<stdlib.h>
// struct student ...
void add(student **list, char* name, int age) {
student* temp = (student *)malloc(sizeof(student));
temp->name = name
temp->age = age;
*list = temp;
*(list++) = (student *)malloc(sizeof(student));
}
void view(student **list) {
student* data = *list;
while(data != '\0') { printf("%s%i", data->name, data->age); *(data++); }
}
main() {
student* list = (student *)malloc(sizeof(student));
char* name = (char *)malloc(sizeof(char));
int age=0;
// inputs for name and age
// do-while(option != EXIT_VALUE);
// inside do-while are the following below
add(&list, name, age);
view(&list);
}
我只根据 View 方法获取最新的学生。
最佳答案
这是有道理的,因为您是为 1 个 student 结构分配空间:
student* list = (student *)malloc(sizeof(student));
你应该这样做:
int list_size = 20;
student* list = (student *)malloc(sizeof(student) * list_size);
name
变量也有同样的问题。
动态链表应该有对下一个和上一个元素的引用。您必须更改程序才能使用:
struct student {
char *name;
int age;
struct student* next;
struct student* previous;
}
关于c - 为什么我的列表只返回最近添加的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5569266/