Hi guys! I'm working on a project in C that requires a few queues, so I started to write a basic linked list style data structure that I could treat as a queue. Once I got the node struct and push() functions written I started testing it to make sure I did my node pointer switching correctly. The queue seems to work fine for all my tests except the one that loops a few times getting user input and storing the input in the queue. Unlike the others, this one does not work at all, all the nodes get overwritten to be the same value. This confuses me as I have a test where it uses push() in a loop and works fine, so I suspect its something to do with how I'm getting/treating the input, or a silly error that I'm somehow missing (pretty new to C still).
Heres the output when the 3 tests are run:
Code:
Repeated calls test:
Current Queue:
str=1
Current Queue:
str=2 str=1
Current Queue:
str=3 str=2 str=1
Current Queue:
str=4 str=3 str=2 str=1
Loop test:
Current Queue:
str=a
Current Queue:
str=b str=a
Current Queue:
str=c str=b str=a
Current Queue:
str=d str=c str=b str=a
Loop input test:
>>
1
>>
Current Queue:
str=1
2
>>
Current Queue:
str=2
str=2
3
>>
Current Queue:
str=3
str=3
str=3
4
>>
Current Queue:
str=4
str=4
str=4
str=4
And here is my full testing program:
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct node{
char * str;
struct node * next;
} node;
//the head of the queue
node * head;
//push a new node to the top of the queue
void push(char * str) {
struct node * new_node = (struct node*) malloc(sizeof(struct node));
new_node->str = str;
new_node->next = head;
head = new_node;
}
//print the queue
void print_q() {
printf("\tCurrent Queue:\n");
struct node *curr = head;
while(curr){
printf("\tstr=%s", curr->str);
curr = curr->next;
}
}
//test pushing input in a loop
void test3(){
printf("Loop input test:\n");
int line_max = 1024; //max input that each line can be
char buf[line_max]; //buffer to store input in
printf(">>\n");
char * str = fgets(buf, line_max, stdin); //get line of input
int i;
for(i = 0; i < 4; i++){
printf(">>\n");
push(str);
print_q();
printf("\n");
str = fgets(buf, line_max, stdin);
}
}
//test pushing in a loop
void test2(){
printf("Loop test:\n");
int i;
for(i = 0; i < 4; i++){
if(i == 0)
push("a");
if(i == 1)
push("b");
if(i == 2)
push("c");
if(i == 3)
push("d");
print_q();
printf("\n");
}
}
//test pushing without loop
void test1(){
printf("Repeated calls test:\n");
push("1");
print_q();
printf("\n");
push("2");
print_q();
printf("\n");
push("3");
print_q();
printf("\n");
push("4");
print_q();
printf("\n");
}
int main(int argc, char const *argv[])
{
test1();
head = NULL;
test2();
head = NULL;
test3();
return 0;
}
Any help pointing me in the right direction would be much appreciated as I can't tell why the 3rd test with user input fails while the others pass