#include<stdio.h>
#include<stdlib.h>
struct node {
char str[200];
int nn;
struct node* next;
};
int number;
struct node* start=NULL;
struct node* current;
//function to insert into the list
void insert() {
struct node* n;
n=(struct node*)malloc(sizeof(struct node));
n->str=malloc(sizeof(char) * 1000);
printf("please enter the data that you would like to insert: ");
gets(n->str);
printf("asdasdasdasd");
n->next=NULL;
if( start==NULL ) {
start->next=n;
current=n;
}
else {
current->next=n;
current=n;
}
printf("done\n");
}
void display() {
current=start;
int i=0;
while( current->next!=NULL ) {
printf("node%d= %s\n",++i,current->str);
current=current->next;
}
printf("this the end");
}
int main() {
char c;
int input;
do {
printf("Select from the following options:\n"
"1.Display list\n"
"2.Add to list\n"
"3.delete from list\n");
scanf("%d",&input);
switch (input) {
case 1: display(); break;
case 2: insert(); break;
// case 3: delete(); break;
default : printf("Please select 1 , 2 or 3\n");
}
printf( "would you like to continue?(y/n)\n");
scanf("%s",&c);
} while(c=='y');
return 0;
}
This is giving me an error in the insert function, A SEGMENTATION FAULT !
I Tried things but I just don’t get the clear picture. I am a bit weak with pointers, actually confused !
Please help me out by telling me what I am doing wrong. Forget about my linked list logic, let it be wrong. I just wanna know why a segmentation fault is occurring !
you have many mistakes, but your crash is because you don’t allocate start
you ask if start is null, and if it is you try to read it by calling start->next it. you need to allocate it first.