c - 为什么我的列表只返回最近添加的元素?

标签 c list pointers struct

再见,

我在 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/

相关文章:

c++ - C2248 - 将 QScopedPointer 传递给函数时无法访问私有(private)成员

c - 为什么 puts 函数不适用于 C++ 中来自套接字的输入字符?

c - 屏幕上看不到实心球体

c - 转换时截断结果不同

javascript - Jquery中的.data()总是返回 "undefined"

python - 如何将字符串列表转换为字符串中各个字符的子列表列表?

c - 将文件中的单词读入简单链表

c++ - C++ 中的多态 vector

c - 为什么++(*p) 没有给出 l-value required 错误?

c - 以列表为元素的数组