问题描述
我正在尝试使用stdlib qsort对字符串数组进行排序。有人可以指出我缺少的步骤。
I am trying to sort an array of strings using stdlib qsort. Could anyone point to me the step I am missing.
int compare(const void* a, const void* b)
{
const char *ia = (const char *)a;
const char *ib = (const char *)b;
return strcmp(ia, ib);
}
//utility to print strings
void print_strs(char name[][10],int len){
int i=0;
len = 5;
for(i=0;i<len;i++){
printf("%s \n",name[i]);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char names[5][10] = {"norma","daniel","carla","bob","adelle"};
int size1 = sizeof(names[0]);
int s2 = sizeof(names)/size1;
print_strs(names,5);
qsort(names,s2,sizeof(char),compare);
printf("\n==================\n");
print_strs(names,5);
return 0;
}
以下是输出中的问题:
1。未排序的字符串
2.数组的第一个字符串不正确(Norma打印为amnor)。
1.unsorted strings 2.first string of the array is incorrect(Norma printed as amnor).
norma
daniel
carla
bob
adelle
==================
amnor
daniel
carla
bob
adelle
推荐答案
您在调用 qsort
时传递了错误的 size
。您正在传递 sizeof(char)
作为单个元素的大小,这是错误的。在您的情况下,每个元素都是一个包含十个字符的字符串。
You are passing wrong size
while calling qsort
. You are passing sizeof(char)
as the size of your individual element, which is wrong. In your case each individual element is a string with ten characters.
因此,您可以通过调用 qsort as:
So, you can correct that by either calling
qsort
as:
qsort(names,s2,sizeof(char) * 10,compare);
或者,因为您已经在
size1 ,您可以这样使用:
Or, as you already have captured this value in
size1
, you can use that, as:
qsort(names,s2,size1,compare);
这篇关于使用qsort对字符串排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!