I'm trying to sort my list alphabetically but i'm having some issues. I have the following:
struct listNodeData
{
int value;
char *position;
char *lastName;
struct listNodeData * next;
};
typedef struct listNodeData listNodeData;
void sortList(listNodeData *List)
{
int swapped;
listNodeData *ptr1;
listNodeData *lptr = NULL;
do
{
swapped = 0;
ptr1 = List->next;
while (ptr1->next != lptr)
{
if (strcmp(ptr1->lastName,ptr1->next->lastName) > 0)
{
swap(ptr1,ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
}
while (swapped);
}
void swap (listNodeData *a,listNodeData *b)
{
char *lastName = malloc(sizeof(char) * 20);
strcpy(lastName,a->lastName);
strcpy(a->lastName,b->lastName);
strcpy(b->lastName,lastName);
}
I am trying to sort the linked list by last name. Right now i'm just trying to swap the last names of my nodes before worrying about swapping the value and position along with the last name. When I compile my program, it works when I run it I get Bus error 10.
I'm not exactly sure why im getting bus error. I've looked at it, and it might have something to do with my strcmp? I'm not sure why because i malloced lastName when I initialized my node, and am mallocing inside the swap function.
The linked list has a dummy header node, so thats why I have
ptr1 = List->next
instead of ptr1 = List
listNodeData *initNode(int number,char *lastName,char *position)
{
listNodeData *newNode;
newNode = malloc(sizeof(listNodeData));
newNode->position = malloc(sizeof(char) * 20);
newNode->position = position;
newNode->lastName = malloc(sizeof(char) * 20);
newNode->lastName = lastName;
newNode->value = value;
newNode->next = NULL;
return (newNode);
}