对动态分配的字符串进行排序
我遇到了奇怪的问题:
int cmp(const void *a, const void *b) {
const char *ia = (const char *) a;
const char *ib = (const char *) b;
return strcmp(ia, ib);
}
char ** names = NULL;
if((names = (char **) calloc(3,sizeof(char*))) == NULL)
{
fprintf(stderr,"Unable to allocate the memory");
return 1;
}
...
names[0] = "c";
names[1] = "b";
names[2] = "a";
printf("before\n");
printf("%s\n",names[0]);
printf("%s\n",names[1]);
printf("%s\n",names[2]);
qsort(names,3,sizeof(char *),cmp);
printf("after\n");
printf("%s\n",names[0]);
printf("%s\n",names[1]);
printf("%s\n",names[2]);
按预期给出:
before
c
b
a
after
a
b
c
但是
names[0] = (char *) calloc(1024,sizeof(char));
names[1] = (char *) calloc(1024,sizeof(char));
names[2] = (char *) calloc(1024,sizeof(char));
scanf("%s",names[0]);
scanf("%s",names[1]);
scanf("%s",names[2]);
printf("before\n");
printf("%s\n",names[0]);
printf("%s\n",names[1]);
printf("%s\n",names[2]);
qsort(names,3,sizeof(char *),cmp);
printf("after\n");
printf("%s\n",names[0]);
printf("%s\n",names[1]);
printf("%s\n",names[2]);
给出了
before
c
b
a
after
b
a
c
为什么字符串排序不正确?
I've got strange problem:
int cmp(const void *a, const void *b) {
const char *ia = (const char *) a;
const char *ib = (const char *) b;
return strcmp(ia, ib);
}
char ** names = NULL;
if((names = (char **) calloc(3,sizeof(char*))) == NULL)
{
fprintf(stderr,"Unable to allocate the memory");
return 1;
}
...
names[0] = "c";
names[1] = "b";
names[2] = "a";
printf("before\n");
printf("%s\n",names[0]);
printf("%s\n",names[1]);
printf("%s\n",names[2]);
qsort(names,3,sizeof(char *),cmp);
printf("after\n");
printf("%s\n",names[0]);
printf("%s\n",names[1]);
printf("%s\n",names[2]);
Gives as expected:
before
c
b
a
after
a
b
c
But
names[0] = (char *) calloc(1024,sizeof(char));
names[1] = (char *) calloc(1024,sizeof(char));
names[2] = (char *) calloc(1024,sizeof(char));
scanf("%s",names[0]);
scanf("%s",names[1]);
scanf("%s",names[2]);
printf("before\n");
printf("%s\n",names[0]);
printf("%s\n",names[1]);
printf("%s\n",names[2]);
qsort(names,3,sizeof(char *),cmp);
printf("after\n");
printf("%s\n",names[0]);
printf("%s\n",names[1]);
printf("%s\n",names[2]);
gives
before
c
b
a
after
b
a
c
Why strings are not sorted correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的比较函数接收数组中项目的地址。您需要取消引用它才能获取数组中的指针:
Your comparison function receives the address of the item in the array. You need to dereference that to get the pointer in the array:
qsort 比较器函数的参数是指向正在比较的参数的指针。我认为你需要额外的取消引用。换句话说,a和b不是char*,而是char**。
The qsort comparator function's arguments are pointers to the arguments being compared. I think you need an additional dereference. In other words, a and b are not char*, they are char**.