为什么我的链表只打印最后一项?
问题描述:
我试图读取文件中的特定行并将其添加到链接列表中,然后将其打印出来。
代码波纹管:当print_list
是谁跑会打印是最后一个条目的唯一的事为什么我的链表只打印最后一项?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct list {
int uid;
char* uname;
struct list* next;
}node;
void push(node ** head, int uid ,char* uname) {
node * new_node;
new_node = malloc(sizeof(node));
new_node->uid = uid ;
new_node->uname=uname;;
new_node->next = *head;
*head = new_node;
}
void print_list(node *head) {
node * current = head;
while (current != NULL) {
printf("%u:%s\n", current->uid,current->uname);
current = current->next;
}
}
int main(int argc, char **argv){
node *current=NULL;
FILE *fp=fopen(argv[1],"r");
if (fp==NULL){
perror("Failed to open file");
exit(EXIT_FAILURE);
}
char s[1024];
const char token[2]=":";
char *stoken;
while(!feof(fp)){
int count=0;
int tempint;
char* tempchar=malloc(sizeof(char));
fgets(s, 1024, fp);
stoken = strtok(s,token);
current=malloc(sizeof(node));
while(stoken != NULL){
if (count==0){
tempchar=stoken;
}
if (count==2){
sscanf(stoken,"%d",&tempint);
}
count++;
stoken=strtok(NULL,token);
}
push(¤t,tempint,tempchar);
}
fclose(fp);
print_list(current);
}
我的问题是。
此输入:
hello:asd:123:foo:ar
hi:proto:124:oo:br
hey:qwe:321:fo:bar
其获取打印的唯一的事情是
321:hey
是我推至极是错还是我print_list?
答
问题是您对待strtok
的结果的方式:您正在将其值设置到节点中,而不是复制它。
添加节点时进行的name
副本:
void push(node ** head, int uid ,char* uname) {
node * new_node;
new_node = malloc(sizeof(node));
new_node->uid = uid;
new_node->uname=malloc(strlen(uname)+1);
strcpy(new_node->uname, uname);
new_node->next = *head;
*head = new_node;
}
你也应该看看,你是在main
功能使用tempchar
的方式。您为单个字符分配一个空间,该空间会被strtok
的结果写入,并泄漏malloc
-ed的内存。
答
这是因为你总是在push()
功能覆盖head
,你应该让NULL
开始,然后检查它是否是NULL
在第一时间并分配给它的第一个节点,然后不reassing什么呢,你的程序因此也有内存泄漏。
此外,你是malloc()
ing节点外的功能,然后在函数内再次,这会导致另一个内存泄漏。
您还应该检查malloc()
是否返回NULL
,指示系统内存不足时发生错误,取消引用NULL
指针是未定义的行为。
而且最后要注意,你必须访问目标变量之前检查scanf()
的返回值,或将再次导致不确定的行为。
答
变化类似如下
char* tempchar;//=malloc(sizeof(char));
fgets(s, 1024, fp);
stoken = strtok(s,token);
//current=malloc(sizeof(node));//don't update like this
while(stoken != NULL){
if (count==0){
tempchar=strdup(stoken);//malloc and strcpy
我认为有必要时跳过的空白行存在。和'while(!feof(fp)){' - >'while(fgets(s,1024,fp)){ – BLUEPIXY