【发布时间】: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;
}
【问题讨论】: