Rohit Goyal
Rohit Goyal

Reputation: 3

Making of linked list by head and node

here's my code in C for making of linked list. Its giving runtime error after the while loop gets executed for one time. Plz help me in correcting my code. (totally confused that where's the error.) I am making a head node first and then adding child nodes to it.

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

typedef struct node nd;
typedef nd *link;

struct node{
    int data;
    link next;
};

typedef struct {
    int size;
    link head;
}list;

void create(link temp)
{
    link new;
    new=(link)malloc(sizeof(nd));
    printf("enter data: ");
    scanf("%d",new->data);
    temp->next=new;
    temp=temp->next;
}

list createlist()
{
    list sl;
    sl.size=0;
    sl.head=0;
    return sl;
}

int main()
{
    list sl;
    sl=createlist();
    link temp;
    temp=sl.head;
    char c;
    while (1)
    {
        printf("Add node?: ");
        scanf(" %c",&c);
        if (c=='y')
           {
            create(temp);
            sl.size++;
           }
        else
            break;
    }
    return 0;
}

Upvotes: 0

Views: 54

Answers (3)

rcgldr
rcgldr

Reputation: 28921

You could use a pointer to pointer for temp. It would be easier to read if you didn't use a typedef for a pointer to node. I haven't tested this, but it should be close:

nd ** create(nd **temp)
{
    nd *new;
    new=(nd *)malloc(sizeof(nd));  /* this cast shouldn't be needed */
    printf("enter data: ");
    scanf("%d",&(new->data));
    new->next = NULL;
    *temp = new;
    return &(new->next);
}
/* ... */

int main()
{
nd **temp;
temp = &(sl.head);
/* ... */
        temp = create(temp);
/* ... */
}

Upvotes: 0

KeithSmith
KeithSmith

Reputation: 774

Initially temp points to NULL. temp = sl.head;

In create(temp) temp->next = new;

You are dereferencing a NULL, address 0x0. I get a segmentation fault when I do that.

Need to change the algorithm. A debugger shows this problem immediately.

Upvotes: 0

user590028
user590028

Reputation: 11728

your createlist() function is returning a reference to a local variable that goes out of scope after it returns. You should instead return a heap based value:

list* createlist() {
    list* sl = (list*)malloc(sizeof(list));
    sl->size=0;
    sl->head=0;
    return sl;
    }

Upvotes: 2

Related Questions