[英]qsort() - sorting an array of strings
Can't seem to find the answer on any question here. 在这里似乎找不到任何问题的答案。 Basically I have this line of code: 基本上我有这行代码:
qsort(Code_Lines, number_of_lines, sizeof(char*), myCmp);
when Code_Lines
is a char**
- points to an array of char*
s when each one contains a string OR pointing to NULL. 当Code_Lines
是char**
-指向char*
的数组,当每个数组包含一个字符串OR或指向NULL时。 What I want to do is to sort all of the strings alphabetically when the strings containing NULL will be at the END of the array. 我想做的是当包含NULL的字符串位于数组的结尾时,按字母顺序对所有字符串进行排序。 Each string within the Code_Lines
will be sorted by its 4 first characters (it's unequal in length of each string - and the first four characters are always different - mentioning a number from 0001
to 9999
), if it's NULL it will just put it in the end of the array. Code_Lines
每个字符串将按其前4个字符排序(每个字符串的长度不相等-前四个字符始终不同-提及从0001
到9999
),如果为NULL,则将其放在数组的末尾。 The variable number_of_lines
is containing the number of lines (code lines) that are in the array, AKA - number of elements (strings, in this case) in the array. 变量number_of_lines
包含数组中的行数(代码行),AKA-数组中的元素数(在这种情况下为字符串)。 myCmp is my compare function and I wrote it this way: myCmp是我的比较函数,我这样写:
int myCmp(const void* element1, const void* element2)
{
int return_value;
if(!element1) //element1 of them is NULL
{
return_value = 1;
}
else if(!element2) //element 2 is NULL
{
return_value = -1;
}
else
{
return_value = strncmp(*((char**)element1), *((char**)element2), 4);
}
return return_value;
}
Any idea what the problem might be ? 知道可能是什么问题吗? The program just crashes there. 程序在那里崩溃。 The function works when the array isn't containing NULL but fails when it does... 该函数在数组不包含NULL时起作用,但在包含NULL时失败
In a qsort
comparison function, the arguments are pointers to the elements of the array you provided, not the elements themselves. 在qsort
比较函数中,参数是指向您提供的数组元素的指针 , 而不是元素本身的指针 。 The elements being compared obviously exist, so these pointers can never by NULL by definition. 被比较的元素显然存在,因此根据定义,这些指针永远不能为NULL。 What you want to check is whether a particular element is NULL
, not the pointer to element: 您要检查的是特定元素是否为NULL
,而不是元素的指针:
int myCmp(const void* element1, const void* element2)
{
int return_value;
char * e1 = *(char **) element1;
char * e2 = *(char **) element2;
if(!e1) //element1 of them is NULL
{
return_value = 1;
}
else if(!e2) //element 2 is NULL
{
return_value = -1;
}
else
{
return_value = strncmp(e1, e2, 4);
}
return return_value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.