我正在尝试创建一个包含5个节点的链接列表并打印它们。我不知道为什么我在打印链表时看不到结果,即使我没有收到错误,我确信我的结构很好。我只看到空白屏幕。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
typedef struct msg *M;
struct msg{
double id;
M next;
};
M queue;
void new_msg(double id);
void printList();
void main()
{
double r;
srand(0);
for(int i=0;i<5;i++){
r = rand() % 100;
new_msg(r);
}
printList(); // PRINT DOES NOT SHOW RESULTS :(
}
void printList()
{
M temp;
while (temp->next != NULL){
temp = temp->next;
printf("MSG ID:%6.3f \n", temp->id);
}
}
void new_msg(double id)
{
M m;
if(queue == NULL)
{
m = malloc(sizeof(struct msg));
}
else
{
m= queue;
queue = queue->next;
}
m->id = id;
m->next = NULL;
}
答案 0 :(得分:1)
问题是,在new_msg()
函数内部,您定义了一个局部变量m
,它永远不会存储,全局queue
永远不会更新。在每次调用中,queue
都等于NULL。
接下来,在您的printList()
功能
temp
已整合while (temp->next != NULL)
可能会在第一次迭代中评估为false。答案 1 :(得分:1)
这两个函数都是无效的并且具有未定义的行为,至少因为在这两个函数中都试图写入或读取未分配的内存。
尝试以下
void printList()
{
for ( M temp = queue; temp != NULL; temp = temp->next; )
{
printf("MSG ID:%6.3f \n", temp->id);
}
}
void new_msg(double id)
{
M m = malloc( sizeof( struct msg ) );
if ( m != NULL)
{
m->id = id;
m->next = queue;
queue = m;
}
}
考虑到虽然有些编译器允许使用返回类型为void的main声明但是这样的声明不符合C标准。
你应该写
int main( void )
答案 2 :(得分:0)
假设new_msg
是正确的,您将打印一个指向虚无的指针列表,可能会导致核心转储。
您的M temp;
未初始化。你可能想要:
M temp = queue;