c语言调用函数为字符串排序

来源:百度知道 编辑:UC知道 时间:2024/05/03 12:10:14
#define SIZE 5
#include<stdio.h>
#include<string.h>
string(char *str[])
{int i,j;
char *s;
for (i=0;i<SIZE-1;i++)
for (j=i+1;j<SIZE;j++)
if (strcmp(str[i],str[j])>0)
{ s=str[i];str[i]=str[j];str[j]=s;}
return(str[SIZE]);
}
main(void)
{char *str[SIZE]={"Father","B","C","Ok","Brother"};
string(str[SIZE]);printf("%s\n",str[SIZE]);
getch();
}
为什么不能输出排序后的字符串?要如何改进才能达到要求?帮帮忙谢谢(我的程序运行是在TC上运行)

这么改:
#define SIZE 5
#include<stdio.h>
#include<string.h>

string(char **str)
{int i,j;
char *s;
for (i=0;i<SIZE-1;i++)
for (j=i+1;j<SIZE;j++)
if (strcmp(str[i],str[j])>0)
{ s=str[i];str[i]=str[j];str[j]=s;}
//return(str[SIZE]);
}

void main()
{
char *str[SIZE]={"Father","B","C","Ok","Brother"};
int i;
string(str);

for(i=0;i<SIZE;i++)
printf("%s\n",str[i]);
getch();
}

最后,printf 里面应该是 str 不是str[SIZE]吧

我也初学者, 不一定对,

首先你的string函数的函数类型没有指定,先定义为char*类型
同时你对str[SIZE]数组的初始化方式得到的每一个指针的类型为只读类型的指针(相当于加上了const关键字),所以初始化的时候改为如下这样的初始化方式吧。

然后main函数修改为
main(void)
{
char str[SIZE][30]=
{
{"Father"},
{"B"},
{"C"},
{"OK"},
{&q