作者:博士吃货 | 来源:互联网 | 2023-05-25 20:31
我正在尝试在C中间创建一个带有空值的冒泡排序.
当数组以某种方式排序时,代码正常工作,因此空值位于数组的末尾(hense"continue"条件有效).
我的数组看起来像这样:[John,David,NULL,Grace,NULL,NULL]我运行这个函数:
void SortContacts(char * people[]) {
int i,j;
char *tempswap;
for (i=0; i 0) {
tempswap = people[j];
people[j] = people[j+1];
people[j+1] = tempswap;
}
}
}
}
当在数组中间执行NULL时,exe崩溃.
1> abligh..:
你不能strcmp
一个NULL
值.虽然你是防范一strcmp
的people[j+1]
存在NULL
,你不检查people[j]
.
尝试以下(未经测试),它只提供一个strcmp
处理a 的函数NULL
类似""的功能.
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 0) {
tempswap = people[j];
people[j] = people[j+1];
people[j+1] = tempswap;
}
}
}
}
如果你想要一个NULL
被视为更大任何其他字符串,请尝试(再次未经测试):
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);
}
如果您希望它们小于任何其他字符串(包括空字符串),请交换return 1
和return -1
.