I want to make a link list that i can add more element to later but the problem i have with the current code is that the all previous elements are overwritten by the last element added.here is my code:
#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;
}
Aucun commentaire:
Enregistrer un commentaire