I’ve been trying to make a simple program that takes the user input, until they press done. And when they do the program will print out everything that they have typed. I feel I have got most of it working, and the program compiles fine but when I enter the input and then press done it will output done for as many lines as I have entered the input. Ive drawn it out, feel that this code should work. Also i’m very new to C. So if anyone can let me know whats wrong or even give me suggestions.
#include <stdio.h>
#include <stdlib.h>
struct llist {
struct llist* nxt;
char* string;
};
void add(struct llist **tail, char* str) {
struct llist* n_ptr = (struct llist*)malloc(sizeof(struct llist));
(**tail).string = str;
(**tail).nxt = n_ptr;
(*tail) = n_ptr;
n_ptr->nxt = (struct llist*)0;
};
void print(struct llist *Head) {
struct llist* ptr;
ptr = Head;
while(ptr->nxt){
printf("%s\n", ptr->string);
fflush(stdout);
(ptr = (ptr->nxt)); }
}
int main() {
char* line = NULL;
size_t size = 100;
char* done = "done";
struct llist head;
struct llist* tail = (struct llist*)malloc(sizeof(struct llist));
tail = &head;
do {
getline(&line, &size, stdin);
add( &tail , line ) ;
} while ( strncmp(line, done, 4) != 0 );
print(&head);
return 0;
}
Your list only contains a pointer to the data, not the data itself. So if the data added to the list changes, the data in the list changes too. For every call to
add,stris the same. So you’ve just added the same pointer to the list over and over.For a quick, ugly fix, change:
to: