2013-10-16 100 views
0

当运行下面的代码时,我的系统挂起。我想了解链接列表和链接列表操作的基础知识。有人可以向我解释我做错了什么(不明白)。多谢你们。打印链表?

#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

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

4

您正在填写DataReadFileList指针指向局部变量。那些在ReadFileList返回时超出范围,因此您导致未定义的行为。