strcmp不会正确地比较指向字符的数组中的2个相邻字符串

时间:2014-04-01 18:42:34

标签: c arrays sorting pointers

我创建了一个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;
}

1 个答案:

答案 0 :(得分:4)

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

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...

中删除所有常用关键字