gpt4 book ai didi

c - strcmp 未正确比较指向字符的指针数组中的 2 个相邻字符串

转载 作者:太空宇宙 更新时间:2023-11-04 06:28:59 25 4
gpt4 key购买 nike

我编写了一个 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;
}

最佳答案

您错误地交换了指向字符串文字的指针,交换函数应该是:

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 关键字

关于c - strcmp 未正确比较指向字符的指针数组中的 2 个相邻字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22794244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com