Reputation: 2342
I'm trying to create a bubble sort with nulls in the middle in C.
The code works ok when the array is ordered in a way so the nulls are at the end of the array (hense the "continue" condition works).
My array looks like this: [John,David,NULL,Grace,NULL,NULL] on which I run this function:
void SortContacts(char * people[]) {
int i,j;
char *tempswap;
for (i=0; i<storage-1; i++) {
for (j=0; j<storage-i-1; j++) {
if (people[j+1]==NULL) {
continue;
}
if (strcmp(people[j],people[j+1]) > 0) {
tempswap = people[j];
people[j] = people[j+1];
people[j+1] = tempswap;
}
}
}
}
When executing with the NULL in the middle of the array the exe crashes.
Upvotes: 0
Views: 1014
Reputation: 25129
You cannot strcmp
a NULL
value. Although you are guarding against a strcmp
of people[j+1]
being NULL
, you don't check people[j]
.
Try the following (untested), which simply provides a strcmp
function which treats a NULL
like "".
int
strcmpwithnull(const char *a, const char *b)
{
return strcmp(a?a:"", b?b:"");
}
void SortContacts(char * people[]) {
int i,j;
char *tempswap;
for (i=0; i<storage-1; i++) {
for (j=0; j<storage-i-1; j++) {
if (strcmpwithnull(people[j],people[j+1]) > 0) {
tempswap = people[j];
people[j] = people[j+1];
people[j+1] = tempswap;
}
}
}
}
If you want a NULL
to be treated as greater than any other string, then try (again untested):
int
strcmpwithnull(const char *a, const char *b)
{
if (a == b)
return 0; /* handles 2 NULLs and two strings at the same location */
else if (!a)
return 1;
else if (!b)
return -1;
else
return strcmp(a, b);
}
If you want them to be less than any other string (including the empty string), swap the return 1
and return -1
.
Upvotes: 6
Reputation: 3191
You want to end up with the nulls at the right of the array. This can be achieved by making nulls strictly greater than any string. You have to encode this into the comparison function.
int cmp(const char *x, const char *y)
{ if(x == 0) return 1;
if(y == 0) return -1;
return strcmp(x, y);
}
Upvotes: 0
Reputation: 3512
Here is the problem
if (people[j+1]==NULL)
{
continue;
}
You need to check both j
and j+1
Also consider What if you have a NULL
in the head of the array ? or you have 2 NULLs
one after another
So you need also to check the j
not only the j+1
you should also check thej
isn't null
Upvotes: 0