Engineering O_o
Engineering O_o

Reputation: 51

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;

}

Upvotes: 0

Views: 91

Answers (2)

greeny
greeny

Reputation: 96

ReadFileList is creating an array of ListNodeType structures on the stack, once that function call ends those variables go out of scope. You can use malloc to allocate memory.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 225252

You're filling in Data in ReadFileList with pointers to local variables. Those go out of scope when ReadFileList returns, so you cause undefined behaviour.

Upvotes: 4

Related Questions