Add to end of a single linked list Segmentation fault C -


i'm trying make c application adds elements @ end of single linked list segmentation fault after read last element.

i use function addatendsll() add element @ end.

//program add elements @ end of single linked list #include <stdio.h> #include <stdlib.h>  //basic declaration of sll struct singlelist{     int data;     struct singlelist *next; };  //add element @ end of sll int addatendsll(struct singlelist **startptr, int value){     struct singlelist *newnode;     newnode = (struct singlelist *)malloc(sizeof(struct singlelist));     if(newnode == null){         printf("\nfailed allocate memory");         return;     }      newnode->data = value;     newnode->next = null;     if(*startptr == null){         *startptr = newnode;     } else {         struct singlelist *temp = null;         temp = *startptr;         while(temp->next != null){             temp = temp->next;         }         temp->next = newnode;     } }  int main() {     int i, value;     struct singlelist *first = null, *temps = null;     temps = first;     for(i = 1; <= 5; i++){         printf("\nenter data:");         scanf("%d", &value);         addatendsll(&first, value);     }      /*****this belive segfault occurs*****/      while(temps->next != null){         printf("%d", temps->data);         temps = temps->next;     }     return 0; } 

any appreciated.

first, fix warnings: make function void instead of int, , remove last return, becomes unnecessary.

next, real problem in code: when set start inside addatendsll function, value of first remains same, because c passes parameters value; includes pointers.

to fix issue, change function accept pointer pointer (i.e. double asterisk), pass &first instead of first it, , add level of dereference parameter inside addatendsll:

void addatendsll(struct singlelist **startptr, int value) {     ...     // change uses of start *startptr, this:     if(*startptr == null){         *startptr = newnode;     }     ... } 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -