打印链表?

时间:2013-10-16 22:15:36

标签: c

运行以下代码时,我的系统挂起。我试图了解链表和链表操作的基础知识。有人可以向我解释我做错了什么(不明白)。谢谢你们。

#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;

}

2 个答案:

答案 0 :(得分:4)

您正在使用指向本地变量的指针填充Data中的ReadFileList。当ReadFileList返回时,这些超出范围,因此导致未定义的行为。

答案 1 :(得分:2)

ReadFileList在堆栈上创建ListNodeType结构数组,一旦该函数调用结束,那些变量超出范围。您可以使用malloc来分配内存。

相关问题