C qsort()中字符串数组上的基本qsort崩溃
我试图使用qsort创建一些基本代码来对字符串数组进行排序,但根据gdb的说法,它在qsort中崩溃了:C qsort()中字符串数组上的基本qsort崩溃,c,arrays,string,crash,qsort,C,Arrays,String,Crash,Qsort,我试图使用qsort创建一些基本代码来对字符串数组进行排序,但根据gdb的说法,它在qsort中崩溃了: #include <string.h> #include <stdlib.h> static int pcmp(const void * a, const void * b) { return strcmp(* (char * const *) a, * (char * const *) b); } int main() { char pn[10][256]
#include <string.h>
#include <stdlib.h>
static int pcmp(const void * a, const void * b)
{
return strcmp(* (char * const *) a, * (char * const *) b);
}
int main()
{
char pn[10][256];
memset(pn, 0, sizeof(char) * 10 * 256);
strcpy(pn[0], "hello");
strcpy(pn[1], "TEST");
strcpy(pn[2], "abc");
strcpy(pn[3], "000000");
qsort(pn, 4, sizeof (char *), pcmp);
}
#包括
#包括
静态int pcmp(常数无效*a,常数无效*b)
{
返回strcmp(*(字符*常量*)a、*(字符*常量*)b);
}
int main()
{
字符pn[10][256];
memset(pn,0,sizeof(char)*10*256);
strcpy(pn[0],“你好”);
strcpy(pn[1],“测试”);
strcpy(pn[2],“abc”);
strcpy(pn[3],“000000”);
qsort(pn,4,sizeof(char*),pcmp);
}
您告诉qsort
您想要排序的是一个由4个char*
组成的数组,但是
char pn[10][256];
实际上,pn
是一个由10个char[256]
组成的数组。这些内容与布局不兼容,qsort
将char[256]
中的第一个字节解释为char*
s。这是未定义的行为,不太可能导致分段错误
要解决此特殊情况,可以将比较更改为
static int pcmp(const void * a, const void * b)
{
return strcmp((const char *) a, (const char *) b);
}
以及对
qsort(pn, 4, sizeof pn[0], pcmp);
“顺便问一下,使pcmp静止的目的是什么?”多米尼克问他。我觉得我所做的足以施展strcmp will I。这是静态原因,这就是你在做“man qsort”的例子中所做的。我复制/粘贴了一些。谢谢,我不知道内部有一些“布局想法”。我认为它只是解析字符串,跳过零字节,解析下一个字符串,而不是真正关心256。请看这篇文章
static int pcmp(const void * a, const void * b)
{
return strcmp((const char *) a, (const char *) b);
}
qsort(pn, 4, sizeof pn[0], pcmp);