So, I wanted to create this code to sort strings in a Linkedlist before inserting. I'm not able to find the error in the code but whenever I try to pass the input into the insert function, it says, 'segmentation fault (core dumped)' - something like that.
What I thought was, to sort, I'd use strcmp() to compare strings, and then based on the value, insert. This is the code,
struct node {
char name[50];
struct node *next;
};
struct node *insert(struct node *head, char *name) {
printf("%s NAME",
name) // To check if the string is correctly passed. Shows above error.
struct node *toinsert,*temp;
toinsert = (struct node *)malloc(sizeof(struct node));
strcpy(toinsert->name, name);
temp = head;
while (temp->next != NULL) {
int a = strcmp(temp->next->name, toinsert->name);
if (a > 0) {
break;
} else {
temp = temp->next;
}
}
toinsert->next = temp->next;
temp->next = toinsert;
return head;
}
int main() {
struct node *head = NULL;
char a[48] = "A";
head = insert(head, a);
return 0;
}
CodePudding user response:
I fixed the following issues:
- Missing headers.
- Syntax error due at
printf()
due to missing;
. - As @HymnsForDisco said you program segfault when it tries to deference a NULL pointer when
head
isNULL
. insert()
doesn't do the right thing if node being added should be the new root.- (refactor)
for
-loop is a better fit thanwhile
-loop. Either option are correct. - (enhancement) added a print function to demonstrate that insert works
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char name[50];
struct node *next;
};
struct node *insert(struct node *head, const char *name) {
struct node *toinsert = malloc(sizeof(struct node));
strcpy(toinsert->name, name);
if(!head || strcmp(name, head->name) <= 0) {
toinsert->next = head;
return toinsert;
}
struct node *temp = head;
for(; temp->next && strcmp(name, temp->next->name) > 0 ; temp=temp->next);
toinsert->next = temp->next;
temp->next = toinsert;
return head;
}
void print(struct node *head) {
for(; head; head=head->next) {
printf("%s\n", head->name);
}
}
int main() {
struct node *head = insert(NULL, "B");
head = insert(head, "A");
head = insert(head, "C");
print(head);
}
and the output is:
A
B
C