[英]How to sort 3D array of chars in C by qsort
我在用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" }
};
在不知道您要介绍的排序规则的情况下,我可以在实现中看到C指针问题。 如果代码成功用于2D情况:
const char name1_ = *(const char **)name1;
我的猜测是,铸造3D外壳不正确:
const char name1_ = *(const char ***)name1;
因为这应该是
const char name1_ = **(const char ***)name1;
因为在3D情况下,您需要两次取消对指针的引用。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.