【发布时间】:2021-07-01 18:58:36
【问题描述】:
在下面给出的代码中, 我无法打印 student.txt 文件的内容。我不确定我的 add 函数是否没有正确 malloc 内容。我的代码中有任何建议。
我的结构
typedef struct student{
char *name;
char *number;
struct student *previous;
struct student *next;
}Student;
main.c
int main (int argc, char **argv) {
FILE *in = fopen("student.txt", "r");
char name[20];
char num[20];
Student *list=NULL;
/* read file into single linked list */
while(fscanf(in, "%s %s",name, num)==2) {
list = add(list,name, num);
}
/* print the list */
printf ("\n\nOriginal list\n********************\n");
print (list);
list.c
Student * add (Student *list, char *name, char *number) {
Student *node = malloc(sizeof(Student));
node->name = strdup(128);
Student *current, *head;
void print (Student *list) {
for(current = head; current ; current=current->next){
printf("%s", current->name);
}
}
node->number = strdup(8);
if(head==NULL){
current = head = node;
} else {
current = current->next = node;
}
return list;
}
学生.txt
John 123
Walter 456
Selena 789
【问题讨论】:
-
??????小心前行,看看会发生什么?
-
strdup(8);笏?打开更多编译器警告,例如使用-Wall或等效项进行编译。 必须是一个C字符串指针,而不仅仅是一个数字。 -
print()函数定义不应在add()函数内。 -
这段代码有很多问题。
head永远不会在你的add函数中初始化,所以一旦你修复了strdup()的东西,它也会爆炸。大概应该是print()函数中的current = list。 -
提示:编写一点代码,然后对其进行测试,然后在您觉得可以正常工作时添加更多代码。看起来你在这里猛烈敲出一大堆代码并让它编译,这并不是一个真正的好方法。现在您有多个问题需要同时诊断。
标签: c linked-list malloc nodes singly-linked-list