c语言二维数组字符串排序,按字符串大小升序排列字符串,但是执行结果“loads”老跑到最前面,求查错

代码
#include<stdio.h>
#include<string.h>

void Sort(char a[25][15]);

int main(void)
{
int c;
char a[25][15]={"Xing","Gnuplot","is","a","command-driven", "interactive","function","plotting","program","If","files","are","given","gnuplot"," loads","each","file","with","the","load","command","in","the","order","specified"};
printf("original:");
for(c=0;c<25;c++){
printf("%s ",&a[c][0]);
}
printf("\n");
printf("sort:");
Sort(a);

for(c=0;c<25;c++){
printf("%s ",&a[c][0]);
}

return 0;
}
void Sort(char a[25][15])
{
int i,j,k;
char temp[20];
char *si,*sj;
for(j=0;j<24;j++){
for(i=j+1;i<25;i++){
si=a[i],sj=a[j];
if(strcmp(sj,si)>0){
strcpy(temp,si);
strcpy(si,sj);
strcpy(sj,temp);
}
}
}
}

跑到前面的字符串前面有个空格!把空格去掉即可;

先解释一下你的问题吧,strcmp函数在进行比较时,遇到'\0'就会结束,而且两个相同的字符串(一个长一个短,比如shao shaoyun,由于第一个先结束,所以判定第一个小!
另外,帮你改正几处地方:(稍作修改的程序)纯手打,希望采纳!!!以后问我就行
#include<stdio.h>
#include<string.h>
void Sort(char a[][15]); //二维的第一维可以不写
void main()
{
int c;
char a[][15]={"Xing","Gnuplot","is","a","command-driven", "interactive","function","plotting","program","If","files","are","given","gnuplot","loads","each","file","with","the","load","command","in","the","order","specified"};
printf("original:\n");//加个换行,程序更清晰
for(c=0;c<25;c++)
{
printf("%s ",a[c]);
}
printf("\n");
printf("sort:\n");//加个换行,程序更清晰
Sort(a);
for(c=0;c<25;c++)
{
printf("%s ",a[c]); //不用写成&a[c][0]!!!后面同理
}
}
void Sort(char a[][15])
{
int i,j;
char temp[20];
for(j=0;j<24;j++) //这里两个for循环的嵌套,你的{}太多了,仔细对比!!!!
for(i=j+1;i<25;i++)
{
if(strcmp(a[j],a[i])>0)//设置两个指针有必要吗???
{
strcpy(temp,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],temp);
}
}

}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-01-22
" loads''前面多了一个空格字符
第2个回答  2013-01-24
同上,求解
第3个回答  2013-01-25
1l答案完全正确
相似回答