我编写了一个程序来接受来自用户的 5 个字符串,然后使用冒泡排序算法按字母顺序显示它们。但是,字符串的显示顺序与输入顺序相同。请告诉我我在这里做错了什么。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sSwap(char *s1, char *s2);
int main(){
char *sList[5],input[100],*p;
int i,j;
puts("Enter 5 strings");
for(i=0;i<5;i++){
gets(input);
sList[i] = (char *)malloc(strlen(input)+1);
strcpy(sList[i],input);
}
puts("");
for(i=3;i>=0;i--){
for(j=0;j<=i;j++){
if(strcmp(sList[j],sList[j+1])>0)
sSwap(sList[j],sList[j+1]);
}
}
for(i=0;i<5;i++)
puts(sList[i]);
return 0;
}
void sSwap(char *s1, char *s2){
char *temp;
temp = s1;
s1 = s2;
s2 = temp;
}
最佳答案
如您所知,您的交换函数获取值并按值交换它们,这意味着当您离开该函数时,更改将不会保存,旧值将返回。试试这个
void sSwap(char **s1, char **s2);
int main(){
char *sList[5],input[100],*p;
int i,j;
puts("Enter 5 strings");
for(i=0;i<5;i++){
gets(input);
sList[i] = (char *)malloc(strlen(input)+1);
strcpy(sList[i],input);
}
puts("");
for(i=3;i>=0;i--){
for(j=0;j<=i;j++){
if(strcmp(sList[j],sList[j+1])>0)
sSwap(&sList[j],&sList[j+1]);
}
}
for(i=0;i<5;i++)
puts(sList[i]);
return 0;
}
void sSwap(char **s1, char **s2){
char *temp;
temp = *s1;
*s1 = *s2;
*s2 = temp;
}
关于c - 无法在 C 中按字母顺序对字符串列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18052765/