再次问候,
我在C上再次遇到此问题,但现在使用struct。 拥有这种学生结构
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);
}
我只根据查看方法获得最新学生。
答案 0 :(得分:3)
这是有道理的,因为你是1个学生结构的分配空间:
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;
}
答案 1 :(得分:1)
你也在做*(data++)
,这是没有必要的。 data++
很好。你真的不应该在任何地方都需要双指针,它只会让事情复杂化。对于分配,很好(如果你认为这是最好的方法),但是为了传递给只读READ指针的其他函数,没有必要。
答案 2 :(得分:0)
我只根据查看方法获得最新学生。
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));
}
请注意,您正在使list
指向新分配的内存位置。它指向的先前值丢失并且还导致内存泄漏。所以只有你得到最后一个条目。您需要实现类似结构的链接列表。
struct student {
char *name;
int age;
struct student *next ;
}
// ....
void add(student **list, char* name, int age) {
// Make sure that every new location is saved in next
// And also the next time when you call this method, it should be
// location of "next" pointing to being passed as parameter.
}
int main()
{
student *list = malloc(sizeof(student)); // No need to type cast malloc
student *preserveHeadNode = list ;
add(&list, name, age);
// .. While viewing pass the "preserveHeadNode" and run the loop until
// student::next == NULL
}
答案 3 :(得分:0)
view
期望list
是指向student的指针数组(以null结尾)。但是,您将它作为指向单个学生的指针在main中分配。然后,每次拨打add
时,您只需重新分配该学生指针。正如克里斯所说,只要有一份学生名单就可能会更好(也更简单)。
答案 4 :(得分:0)
如果要将列表实现为数组,则需要一种策略来在列表大于初始数组大小时重新分配列表。一个典型的策略是选择一个任意大小来处理大多数情况而不浪费大量内存,然后在达到绑定时加倍。所以,假设您从一个8元素列表开始。添加第9个元素时,它会将数组重新分配给16个元素的列表。
另一种策略是使用链接列表,在其中向结构添加结构指针(通常命名为“next”)并使用它来迭代列表。这使得分配和遍历变得更加简单,尽管列表检索变为O(n)操作而不是O(1)操作,这意味着随着列表变大,从列表中获取特定元素需要更长的时间。
答案 5 :(得分:0)
您有两种选择。
创建链接列表,您可以插入所需数量的学生。 (每个学生也有下一个学生的指针,如果有的话,它是NULL)
按照karlphillip的建议创建学生指针数组,但添加新学生的方法需要实现位置搜索或存储此位置。 (你必须弄清楚你应该在哪里存储指向学生的指针)