struct - Appending Linked List in C seg fault errors -


i having trouble adding integers end of linked list. new c , had part of program working (the push function). want return pointer struct node, , not quite sure going wrong in append function.

~thanks.

 enter code here    //node.h   #ifndef node_h  #define node_h   struct node{    int val;    struct node *next;  };   int length(struct node *);  struct node* push(struct node *, int);     //adds integer front of list.  struct node* append(struct node *, int);   //adds integer of list.  void print(struct node *, int);   #endif    //node.c   #include "./node.h"  #include<stdlib.h>  #include<stdio.h>   int length(struct node *current){     if(current->next != null)     return 1 + length(current->next);  else   return 1;  }   struct node* push(struct node *head, int num){      struct node *temp = malloc(sizeof(struct node));     temp->val = num;     temp->next = head;     head = temp;     temp = null;     return head;     }      struct node* append(struct node *current, int num){         if(current != null){        append(current->next, num);        }         else{          struct node* temp = malloc(sizeof(struct node));          temp->val = num;        temp->next = null;        current = temp;        return current;         }        }     void print(struct node* head, int size){     printf("the list %i", size);    printf(" long \n");    struct node* temp;    temp = head;    while(temp != null){    printf("%d", temp->val);    printf(" ");    temp = temp->next;    }    printf(" \n");    }     //main    #include "./node.h"   #include<stdlib.h>   #include<stdio.h>    int main(){      char ans[2];     int num;     struct node* head = null;      do{      printf("enter integer linked list: ");      scanf("%d", &num);       head = append(head, num);      printf("add integer linked list? (y or n) ");      scanf("%1s", ans);      }while(*ans == 'y');       print(head, length(head));       return 0;      } 

i think missing recursive part of function needs set current->next. has effect of setting every node's next pointer until end of list, when set newly malloced node.

struct node* append(struct node *current, int num){         if(current != null){          current->next = append(current->next, num);          return current;        }        else {          struct node* temp = malloc(sizeof(struct node));          if (temp == null) abort();          temp->val = num;          temp->next = null;          return temp;        } }  

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -