I am having trouble printing the correct values of my linked list after nodes have been inserted into it. The struct for my linked list is the following.
#include <stdio.h>
#define SIZE 50
struct car{
int car_number;
int speed;
int consumption;
int reliability;
};
struct teams{
char team_name[SIZE];
struct elem_fila *car_list_root;
};
struct elem_fila{
struct car car_info;
struct elem_fila *next_car;
};
The struct teams is a struct that will have a linked list of elem_fila structs which each have information about a car.
My insertion code is the following:
void insert(struct car c, struct elem_fila **root){
struct elem_fila *aux, *next, *previous;
aux = (struct elem_fila *) malloc(sizeof(struct elem_fila));
//Something went wrong
if (aux == NULL) {
return;
}
aux->car_info = c;
aux->next_car = NULL;
printf("%d\n", aux->car_info.speed);
//If the root is null
if (*root == NULL){
*root = aux;
printf("%d\n", (*root)->car_info.speed);
}
//If the root is not null
else{
printf("%d", aux->car_info.speed);
previous = *root;
next = (*root)->next_car;
while (next != NULL) {
previous = next;
next = next->next_car;
}
previous->next_car = aux;
aux->next_car =NULL;
}
printf("%d", (*root)->car_info.speed);
}
The insertion algorithm works as following: every new element gets put on the back of the list.Here the "prints" work fine even when inserting a new element, the root element still prints the values put in before.
But when I call my print list algorithm everything goes wrong and it prints out random values (probably memory addresses). Here is the code:
void printList(struct elem_fila *root){
struct elem_fila *current;
printf("%d\n", (root)->car_info.speed);
current = root;
while(current != NULL ){
printf("Numero carro: %d, Velocidade: %d, Consumption: %d, Reliability:%d\n",current->car_info.car_number,
current->car_info.speed,
current->car_info.consumption,
current->car_info.reliability);
current = current->next_car;
}
return;
}
Here the printf on the second line instead of giving the number 30 (the one I was inserting as a test) it was giving me the number 741355568. I am calling the functions as following :
void teste2(){
strcpy(team_list[0].team_name,"Team A");
struct car carro = { 10, 30, 50, 60};
struct car carro2 = { 100, 80, 90, 70};
insert(carro, &team_list[0].car_list_root);
insert(carro2, &team_list[0].car_list_root);
printf("%s" ,team_list[0].team_name);
printList(team_list[0].car_list_root);
}
Note: team_list is an array of team structs. Note2: the team's name is printing like intended
If anyone could help I would appreciate it a lot. I have been trying for a long time but can't seem to find the problem!