简体   繁体   中英

I cannot traverse through my linked list, after creating an array of nodes

I've created an array of nodes for a linked list however when I attempt to traverse to print my linked list I crash. My traversal works a treat when I do not create an array of nodes so I figure this snippit of code is my problem.

   typedef struct node {
book data;
struct node *next;
} *Node;

Node newNodes[100];
int i = 0;
for (i=0; i<n; i++) 
{
    newNodes[i] = (Node)malloc(sizeof(struct node)); 
    newNodes[i]->next = NULL;
    newNodes[i]->data.time = NULL;
    newNodes[i]->data.format = NULL;     
}


//return struct that holds the array;

Clearly I've done something wrong, insert_node is a really simple insert at front algorithm by the way. Can anyone see where I've gone wrong?

Can anyone see where I've gone wrong?

The posted code shows that you have created 100 pointers and assigned memory to them from the value returned by malloc . However, you haven't linked them up together to form a linked list.

Perhaps you meant to use:

for (i=0; i<n; i++) 
{
    newNodes[i] = (Node)malloc(sizeof(struct node)); 
    newNodes[i]->next = NULL;
    newNodes[i]->data.time = NULL;
    newNodes[i]->data.format = NULL;     
}

// Make the links between the nodes.
for (i=0; i<n-1; i++) 
{
   newNodes[i]->next = newNodes[i+1];
}

That will make newNodes[0] the head of the linked list.

PS

Using a typedef called Node that is a pointer is very confusing, at least to me. I would recommend using:

typedef struct node {
    book data;
    struct node *next;
} Node;

typedef Node* NodePtr;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM