【问题标题】:strcmp does not compare 2 adjacent strings in array of pointer to characters properlystrcmp 不能正确比较字符指针数组中的 2 个相邻字符串
【发布时间】:2014-04-01 18:42:33
【问题描述】:

我制作了一个 c 程序来按字母顺序排列 10 个字符串数组,但我在使用 strcmp() 时遇到了困难。此行由字符串处理比较函数组成,不比较右侧的字符串。到目前为止,这是我的代码。感谢您的帮助!

#include <string.h>
#include <stdio.h>
#define SIZE 10

void bubbleSort(char * const townAry[SIZE], size_t size);

int main(void)
{
    size_t i;
    char * const townPtr[SIZE] = {"Alviso","Milpitas","Berryessa","Alum Rock","Los Gatos",
                                "Campbell","Cupertino","Sagatora","Sunnyvale","Mountain View"};

    bubbleSort(townPtr,SIZE);

    for (i = 0; i < SIZE; ++i)
    {
        printf("%s\n",townPtr[i]);
    }
    puts("");
    // expected output:
    // Alum Rock
    // Alviso
    // Berryessa
    // Campbell
    // Cupertino
    // Los Gatos
    // Milpitas
    // Mountain View
    // Sagatora
    // Sunnyvale
    return 0;
}

void bubbleSort(char * const townAry[SIZE], size_t size)
{
    void swap(char *town1Ptr, char *town2Ptr);
    unsigned int pass;
    size_t j;

    for (pass = 0; pass < size - 1; ++pass)
    {
        for (j = 0; j < size - 1; ++j)
        {
            if(strcmp(townAry[j], townAry[j + 1]) > 0) // problem: this line doesn't compare 2 adjacent strings
            {
                swap(townAry[j], townAry[j + 1]);
            }
        }
    }
}

void swap(char *town1Ptr, char *town2Ptr)
{
    char * hold = town1Ptr; 
    *town1Ptr = *town2Ptr;
    *town2Ptr = *hold;
}

【问题讨论】:

    标签: c arrays sorting pointers


    【解决方案1】:

    您错误地将指针交换为字符串文字,交换函数应该是:

    void swap(char **town1Ptr, char **town2Ptr)
    {
        char* hold = *town1Ptr; 
        *town1Ptr = *town2Ptr;
        *town2Ptr = hold;
    }
    

    确保将变量正确传递给交换函数

    swap(&townAry[j], &townAry[j + 1]);
    

    并从 char * const townPtrvoid bubbleSort(char * const... 中删除所有 const 关键字

    【讨论】:

    • @self 我需要修复这条线 if(strcmp(townAry[j], townAry[j + 1]) > 0) 因为它不起作用。交换功能是另一个问题,以后可能会出现。
    • 另外,参数声明char * const townAry[SIZE]中的SIZE也没用。声明等同于char *const townAry[],它等同于char ** const townAry。它实际上只是一个指针,而不是一个数组。数组实际上不能传递给 C 中的函数;声明被调整为指针类型。声明的数组形式,具有大小,可以在传递固定大小的数据时用作文档,但如果您还传递了size 参数,那就没有实际意义了。跨度>
    • @user3077220 该行似乎不起作用,因为您正在对数据进行加扰。您的交换例程试图交换两个字符串的第一个字符,而不是字符串本身。 (由于字符串是字符串文字,这实际上是未定义的行为:字符串文字不可修改。)如果您的编译器和运行时实际上允许修改文字,那么您的 swap("abc", "def") 会将这些输入变为 "dbc", "aef"。但是,在许多现代环境中,尝试修改字符串文字会使程序崩溃。
    • 我明白我的问题了,你们有没有其他的方法来制作这种程序?我的解决方案好吗?
    • @Kaz 修复后得到结果:Alum Rock Alum Rock Alum Rock Alum Rock Campbell Campbell Cupertino Mountain View Mountain View Mountain View 为什么会这样?
    猜你喜欢
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    相关资源
    最近更新 更多