【发布时间】:2021-06-17 22:13:43
【问题描述】:
在将节点插入链表后,我无法打印链表的正确值。 我的链表结构如下。
#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;
};
结构体 team 是一个结构体,它有一个 elem_fila 结构体的链表,每个结构体都有关于汽车的信息。
我的插入代码如下:
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);
}
插入算法的工作原理如下:每个新元素都放在列表的后面。这里的“打印”即使在插入新元素时也能正常工作,根元素仍然会打印之前放入的值。
但是当我调用我的打印列表算法时,一切都出错了,它会打印出随机值(可能是内存地址)。代码如下:
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;
}
第二行的 printf 没有给出数字 30(我作为测试插入的那个),而是给出了数字 741355568。我调用的函数如下:
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);
}
注意:team_list 是一个团队结构数组。 注意 2:团队名称按预期打印
如果有人可以提供帮助,我将不胜感激。试了半天也没找到问题!
【问题讨论】:
-
清理缩进将是一个好的开始。
-
team_list是如何初始化的?在开始插入之前你确定team_list[0].car_list_root == NULL吗? -
您似乎缺少一些包含,并且您的 cast of malloc 可能隐藏了一些由此产生的问题。
-
修复了这些问题后,即使在 valgrind/AddressSanitizer 下,您的程序也可以正常运行且输出正确,即使在 valgrind/AddressSanitizer 下(当然也存在内存泄漏)。
标签: c pointers memory struct linked-list