Problem with linked list and strings

Joined
Oct 17, 2010
Messages
2
Reaction score
0
Hello, i created a linked list but it has problem to put in the nodes the content which get from the gets() function. ie put in all nodes the last input. But the code works correctly in the comments.

Any idea?

Here is my code:

#include <stdio.h> /* for printf */
#include <stdlib.h> /* for malloc */
#include <string.h>

struct node
{
char *data;
struct node *next; /* pointer to next element in list */
};

struct node *list_add(struct node **p, char *i)
{
struct node *n = (node *)malloc(sizeof(struct node));
if (n == NULL)
return NULL;

n->next = *p; /* the previous element (*p) now becomes the "next" element */
*p = n; /* add new empty element to the front (head) of the list */
n->data = i;

return *p;
}


void list_print(struct node *n)
{
if (n == NULL)
{
printf("list is empty\n");
}
while (n != NULL)
{
printf("print %s\n", n->data);
n = n->next;
}
}

int main(void)
{

int i;
char buf[1024];
struct node *n = NULL;


for (i=0;i<5;i++){

gets(buf);
list_add(&n, buf);


}
//list_add(&n, "aa");
//list_add(&n, "bb");
//list_add(&n, "cc");
//list_add(&n, "dd");
//list_add(&n, "ee");
list_print(n);




return 0;

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top