c - 无法在 C 中按字母顺序对字符串列表进行排序

标签 c string algorithm sorting

我编写了一个程序来接受来自用户的 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/

相关文章:

c - 很好的介绍(伪)随机数生成

javascript - 如何限制圆圈在一个范围内的移动?

c - 空字符串结束循环

C - 动态内存分配

string - Raku:从字符串中捕获组的一行表达式?

javascript - jQuery - 如果选中多个复选框,并且为每个复选框添加一个字符串到文本框

r - 通过最小化 R 中的方差对数据进行分组

c - 查找数组中元素之间的匹配项? (C)

c - 使用 strtok 比较 strtok 函数嵌套结果中的两个单词的问题

正则表达式匹配字符串中重复两次的前几个字符