I have a program written in C. And I'm struggling with an effect that I cannot understand. An application reads a sequence of words as command line input. When reading an input, it puts one word into the list. Then prints the list. Which makes me think, why the values โโadded by the user, the loop prints correctly, while the values โโadded inside the loop are not. I mean, what values โโare entered by the user, only the last will be printed. And besides, it will be printed as many times as the number of values โโis entered. The two main suspects are the push and printList methods:
void push(struct List * list, char* newValue){
assert(list != NULL);
assert(newValue != NULL);
Node* node = createNode();
node->data = newValue;
node->next = NULL;
if(list->firstNode != NULL){
node->next = list->firstNode;
list->firstNode = node;
}
else list->firstNode = node;
}
void printList(struct List * list){
assert(list != NULL);
Node *node = list->firstNode;
while(node->next != NULL){
printf("%s ", node->data);
node = node->next;
}
if(node != NULL) printf("%s ", node->data);
}
But I could not find mistakes there. What I have done is comparing the behavior with and without a while loop:
int main(){
struct List* list = createList();
char s[256];
int a;
push(list, "he");
push(list, "bee");
push(list, "gee");
while(scanf("%s", &s) == 1) push(list, s);
printList(list);
}
The result obtained:
c c c gee bee he
:
a b c
,
c b a gee bee he
? .
P.S. defs , :
typedef struct Node {
char* data;
struct Node *next;
} Node;
typedef struct List {
struct Node *firstNode;
} List;
Node *createNode(){
Node* node = malloc(sizeof(struct Node));
assert(node != NULL);
node->data = "";
node->next = NULL;
return node;
}
List *createList(){
List* list = malloc(sizeof(struct List));
list->firstNode = NULL;
assert(list != NULL);
return list;
}