1

I tried to implement a function to append nodes to a linked list using the hints on cs50 study but all i get is (runtime error). Here's my code

#include <stdio.h>
#include <stdlib.h>

#define SIZE 10

typedef struct node
{
    // the value to store in this node
    int n;

    // the link to the next node in the list
    struct node* next;
}
node;

node* head = NULL;

void append(int i)
{
    node* new;
    new->n = i;
    new-> next = NULL;
    // if it's the first element ,make head point to new node
    if(head == NULL )
    {
        head= new;
        return;
    }

    for(node* ptr = head ; ptr != NULL ; ptr= ptr->next)
    {    // find the last element
        if(ptr->next == NULL )
        {
            ptr->next = new;
            break;
        }
    }
}

int main(int argc, char* argv[])
{
    // creating list
    printf("Appending ints 0-%i onto the list...\n", SIZE - 1);
    for (int i = 0; i < SIZE; i++)
    {
        append(i);
    }
    printf("done!\n");

    // printing out list
    printf("Your list contains ");
    for (node* ptr = head; ptr != NULL; ptr = ptr->next)
    {
        printf("%i ", ptr->n);
    }
    printf("\n");

    return 0;
}
2

You have a very small mistake. See your append function:

void append(int i)
{
    node* new;
    new->n = i;
    new-> next = NULL;

You declare new as a pointer to a node, but you never reserve memory for this node. To fix it change it to

node* new = malloc(sizeof(node));

or even better

node* new = calloc(1, sizeof(node));

and your code will work great. Good job! Your code is really good, but here are some tips to make it better.

Tip #1

This should go unsaid, but you should always, always, always free() the memory you reserved at the end of your program. So don't forget to free() all the nodes you malloced or calloced.

Tip #2

Since the word new is a reserved word in some other languages, it might cause confusion. Better replace it with new_node or something similar.


If this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark. And don't forget to keep coding!

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .