struct - Linked list in C seg faults -
having seg fault erros code posted below. new c , have been having trouble it. in main made struct node* head (pointer struct node) , assigned null. send struct node * head push function should insert user defined integers front of list. believe having issues inside push function, aprecciated.
~thanks
//node.h struct node{ int val; struct node* next; }; int length(struct node *); struct node* push(struct node *, int); void print(struct node *, int); //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; return head; } 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 program #include "./node.h" #include<stdlib.h> #include<stdio.h> int main(){ char ans; int num; struct node* head = null; do{ printf("enter integer linked list: "); scanf("%d", &num); head = push(head, num); printf("add integer linked list? (y or n) "); scanf("%1s", &ans); }while(ans == 'y'); print(head, length(head)); return 0; }
scanf
read n+1
characters provided buffer when use %ns
because of null terminator.
use buffer of size 2 (char ans[2];
) , check first character (ans[0] == 'y'
). no longer need take address of ans
when calling scanf
).
Comments
Post a Comment