我在C中使用qsort()
对char的3D数组进行排序时遇到问题。
我想按字符串的长度对数组进行排序。
我发现这个代码用于对2D数组进行排序:
int compare(const void *name1, const void *name2)
{
const char *name1_ = *(const char **)name1;
const char *name2_ = *(const char **)name2;
return strcmp(name1_, name2_);
}
我将代码修改为:
int compare(const void *name1, const void *name2)
{
const char *name1_ = *(const char ***)name1;
const char *name2_ = *(const char ***)name2;
if(strlen(name1_)>strlen(name2_))
{
return 1;
}
if(strlen(name1_)<strlen(name2_))
{
return -1;
}
else
{
return 0;
}
}
但这不起作用,我不知道该怎么做。
例如。我想像这样排序数组:
char * array1 [][2] = {
{ "murderer", "termination specialist" },
{ "failure", "non-traditional success" },
{ "specialist", "person with certified level of knowledge" },
{ "incorrect answer", "alternative answer" }
};
采用以下格式:
char * array1 [][2] = {
{ "incorrect answer", "alternative answer" },
{ "specialist", "person with certified level of knowledge" },
{ "murderer", "termination specialist" },
{ "failure", "non-traditional success" }
};
答案 0 :(得分:0)
在不知道您想要介绍的排序规则的情况下,我可以在您的实现中看到C指针问题。如果代码成功用于2D案例:
const char name1_ = *(const char **)name1;
我的猜测是3D情况的投射不正确:
const char name1_ = *(const char ***)name1;
因为这应该是
const char name1_ = **(const char ***)name1;
因为在3D情况下你需要两次取消引用指针。
答案 1 :(得分:-1)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char *Row[2];
int compare(const void *row1, const void *row2){
const Row *name1 = (const Row*)row1;
const Row *name2 = (const Row*)row2;
return strlen((*name2)[0]) - strlen((*name1)[0]);
}
/* or
int compare(const void *row1, const void *row2){
const char *name1 = *(const char**)row1;
const char *name2 = *(const char**)row2;
return strlen(name2) - strlen(name1);
}
*/
int main(){
char * array1 [][2] = {
{ "murderer", "termination specialist" },
{ "failure", "non-traditional success" },
{ "specialist", "person with certified level of knowledge" },
{ "incorrect answer", "alternative answer" }
};
qsort(array1, sizeof(array1)/sizeof(*array1), sizeof(*array1), compare);
{//check
int i;
for(i=0;i<4;++i)
printf("\"%s\", \"%s\"\n", array1[i][0], array1[i][1]);
}
return 0;
}