Click here to Skip to main content
15,884,628 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am new to the concept of linked list and I need some help. I am writing a code which first builds a linked list and then function which gives the value of nth data in the list. But the code doesn't run. I am using Codeblocks so it doesn't tell the exact error, the process simple terminates. I cant understand why. Any help would be highly appreciated. Here's the code:

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

struct node{
    int data;
    struct node* ptr;
};
void push(struct node**,int);
void build(struct node**);
int getn(struct node*, int);

int main(){
    int n;
    struct node first;
    struct node* head;
    *head = first;
    first.data = 1;
    first.ptr = NULL;
    build(&head);
    n=getn(head,1);
    return 0;
}


void build(struct node** send){
    push(send,344);
    push(send,65);
    push(send,44);
}

void push (struct node** a, int datum){
    struct node* temp;
    temp = malloc(sizeof(struct node));
    temp->data = datum;
    temp->ptr =  *a;
    *a = temp;
}

int getn(struct node* top, int index){
    int n,k;
    struct node* current = top;
    for(n=0; n<index;n=n+1){
        k = current->data;
        current = current->ptr;
    }
    return k;
}
Posted
Updated 4-Oct-14 2:08am
v4
Comments
Sergey Alexandrovich Kryukov 4-Oct-14 6:06am    
To understand why, just use the debugger.
—SA
Member 11129008 4-Oct-14 8:10am    
debugging helped. Thanks :)
Sergey Alexandrovich Kryukov 4-Oct-14 8:14am    
My pleasure.
—SA
Richard MacCutchan 4-Oct-14 6:08am    
That code will not even compile, so I do not understand how you can say it runs. You need to fix all your compiler errors first. You should also spend some time studying pointers and indirection, in your C reference guide.
Member 11129008 4-Oct-14 7:25am    
the code is compiling with zero errors and warnings but not running.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900