[英]Printing a linked list?
When running the following code my system hangs. 运行以下代码时,我的系统挂起。 I am trying to understand the basics of linked lists and linked list manipulation.
我正在尝试了解链接列表和链接列表操作的基础。 Could someone please explain to me what I did wrong (don't understand).
有人可以向我解释我做错了什么(不明白)。 Thanks guys.
多谢你们。
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNodeT
{
float power;
struct ListNodeT *nextPtr;
}ListNodeType;
void ReadFileList(ListNodeType *Data);
int main(void)
{
ListNodeType a;
ReadFileList(&a);
ListNodeType *node = &a;
do
{
printf("%f", node->power);
node = node->nextPtr;
}while(node != NULL);
return EXIT_SUCCESS;
}
void ReadFileList(ListNodeType *Data)
{
ListNodeType new[2];
Data->nextPtr = &new[0];
new[0].nextPtr = &new[1];
new[1].nextPtr = NULL;
Data->power = 0.1;
new[0].power = 1.2;
new[1].power = 2.3;
}
You're filling in Data
in ReadFileList
with pointers to local variables. 您正在使用指向局部变量的指针填充
ReadFileList
中的Data
。 Those go out of scope when ReadFileList
returns, so you cause undefined behaviour. 当
ReadFileList
返回时,它们超出范围,因此会导致未定义的行为。
ReadFileList is creating an array of ListNodeType structures on the stack, once that function call ends those variables go out of scope. ReadFileList在堆栈上创建一个ListNodeType结构的数组,一旦该函数调用结束,这些变量将超出范围。 You can use malloc to allocate memory.
您可以使用malloc分配内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.