2015-04-19 66 views
0

我想创建一个链接列表,我可以在稍后添加更多元素,但是现在的代码中存在的问题是,所有以前的元素都被添加的最后一个元素覆盖。这里是我的代码:将元素添加到链接列表(C)

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 

struct node { 
    char *name; 
    struct node *next; 
}*head; 



void add(char *str) { 
    struct node *temp; 
    temp=(struct node *)malloc(sizeof(struct node)); 
    temp->name=str; 

    if (head== NULL) { 
     head=temp; 
     head->next=NULL; 

    } else { 
     temp->next=head; 
     head=temp; 
    } 
} 

void display(struct node *r) { 
    r=head; 
    if(r==NULL) 
     return; 

    while(r!=NULL) { 
     printf("%s ",r->name); 
     r=r->next; 
    } 

    printf("\n"); 
} 

int main() 
{ 
    char *str; 
    struct node *n; 
    head=NULL; 
    while(scanf("%s",str) == 1) { 
     add(str); 
     display(n); 
    } 

    return 0; 
} 
+1

为什么没有在缩进代码更好的尝试?也许学习使用调试器是当天的顺序 –

+0

函数'display'不需要'r'作为参数。尝试'void display(){struct node * r = head; ...}' – francis

+0

我明白了!非常感谢你! – benson

回答

5

变化

int main() 
{ 
    char *str; 

int main() 
{ 
    char str[100]; // Or some other value to give scanf somewhere to put the data 

然后在添加(假设这本功能离子可在您的设定)

temp->name=strdup(str); 

我离开释放内存作为练习读者

+0

Ps:'strdup'不可用'malloc(strlen(str)+ 1); strcpy(temp-name,str);' –

+1

此外,'display(n);'应该是'display(head);' –

+0

@AntoJurković - 正确 - 我没有那么远:-( –

3

在你add您使用建设

temp->name=str; 

它不执行字符串复制,它只是使temp->name指向str。您应该改用strcpy。喜欢的东西

temp->name = (char*) malloc(strlen(str)+1); 
strcpy(temp->name, str); 

而在你的主要功能应变量str分配内存,在scanf使用它之前。

char* str = (char *)malloc(255); 
... 
free(str); 

char str[255]; 
+2

它被标记为C - so new out - 尝试malloc。(还需要为空字符添加一个) –

+0

@Ed Heal你是完全正确的,我将正确答案 – kvorobiev

+0

你不需要在malloc上进行转换 –