qsort()给字符串排序问题

rzzat1478 2008-10-23 09:45:17
#include<stdlib.h>
#include<stdio.h>

static int comp(const void *a, const void *b)
{
return strcmp( * (const char ** )a,* (const char **) b);
}
void sortStrings(const char * array[])
{
int num;
for (num=0; array[num]; num++){};
qsort(array, num, sizeof( * array), comp) ;
}
main()
{
int i;
char *string[4]={"boy","girl","apple","dog"};
sortStrings(string);/*这行有错误*/
for(i=0;i<4;i++)printf("%d",string[i]);
system("Pause");
}
源代码如上,提示错误: [Warning] passing arg 1 of `sortStrings' from incompatible pointer type ,不知道为什么错?
...全文
775 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
weidong0210 2008-10-23
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 tian428 的回复:]
for (num=0; array[num]; num++){}; 无法求出数组的元素个数
[/Quote]
不知道你想干什么 for 循环没有你这样的写法 num++ 要加到什么时候?
tian428 2008-10-23
  • 打赏
  • 举报
回复
for (num=0; array[num]; num++){}; 无法求出数组的元素个数
tian428 2008-10-23
  • 打赏
  • 举报
回复
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

static int comp(const void *a, const void *b)
{
return strcmp( *(const char ** )a, *(const char **) b);
}
void sortStrings( const char * array[], int num)
{
qsort(array, num, sizeof(char *), comp) ;
}
int main()
{
int i;
char *string[4]={"boy","girl","apple","dog"};
sortStrings((const char **)string, 4);
for(i=0;i <4;i++)printf("%s\n",string[i]);
system("Pause");
return 0;
}
rzzat1478 2008-10-23
  • 打赏
  • 举报
回复
我还发现void sortStrings(const char * array[]) 中若去掉const或像3楼那样改的话能编译成功但一运行就出现“。。。。。该内存不能为'read'.."错误
rzzat1478 2008-10-23
  • 打赏
  • 举报
回复
[Warning] passing arg 1 of `qsort' discards qualifiers from pointer target type
[Warning] passing arg 1 of `sortStrings' from incompatible pointer type
Quote=引用 4 楼 ysuliu 的回复:]
什么问题,你把问题贴出来。。
还是
sortStrings(string);/*这行有错误*/
这个地方?


[/Quote]
ysuliu 2008-10-23
  • 打赏
  • 举报
回复
什么问题,你把问题贴出来。。
还是
sortStrings(string);/*这行有错误*/
这个地方?

[Quote=引用 2 楼 rzzat1478 的回复:]
还是有问题啊
[/Quote]
tian428 2008-10-23
  • 打赏
  • 举报
回复
sortStrings((const char **)string);
rzzat1478 2008-10-23
  • 打赏
  • 举报
回复
还是有问题啊
ysuliu 2008-10-23
  • 打赏
  • 举报
回复
void sortStrings(const char * const array[])

再加个const。

你的"boy","girl","apple","dog" 这些数据都是放在常量区的,具有const属性,所以不能传递给非const的指针

69,378

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧