使用strcmp和strcpy按字母排序省份名称时的数组初始化问题
问题分析与修正方案
你的代码存在多个关键错误,导致数组无法正常打印和排序,下面逐一说明并给出修正后的代码:
1. 字符串数组初始化错误
原代码用单引号'Ontario'包裹字符串是错误的——单引号仅用于单个字符,字符串必须用双引号"Ontario"。同时,存储多个字符串的数组需声明为指针数组或二维字符数组,原声明char strStates[8]只能存储单个字符串,无法容纳多个省份名称。
2. 打印逻辑错误
原循环for (x = 0; x < 7; x++) { printf("\n%s", strStates); }每次都打印整个数组的首元素,正确写法应打印strStates[x],即每个索引对应的省份。
3. 函数定义与调用错误
sort函数返回值声明为char,但实际无需返回任何值,应改为void。- 调用
sort时传入的strStates[x]和strSorted[x]是单个字符,而函数需要的是字符串数组,正确应传入整个数组。 sort函数参数应定义为char *string[](字符串指针数组),而非char string[];内部使用strcmp时,直接传入string1[x]和string1[y]即可,无需额外错误操作。- 函数内的
string[y]是未定义变量,属于笔误。
4. 排序逻辑错误
原排序的循环范围(x<3、y<4)不符合实际省份数量(6个),应遍历所有元素;交换字符串时无需额外的strSorted数组,用一个临时字符数组即可完成。
修正后的代码
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> // 排序函数:接收字符串指针数组和元素数量 void sort(char *string[], int count) { int x, y; // 临时字符串,用于交换时存储数据 char temp[50]; // 冒泡排序实现 for (x = 0; x < count - 1; x++) { for (y = x + 1; y < count; y++) { // 比较两个字符串,前者大于后者则交换 if (strcmp(string[x], string[y]) > 0) { strcpy(temp, string[x]); strcpy(string[x], string[y]); strcpy(string[y], temp); } } } } int main() { // 字符串指针数组存储省份名称,双引号包裹字符串 char *strStates[] = { "Ontario", "Quebec", "Manitoba", "Alberta", "British Colombia", "Nova Scotia" }; // 计算省份数量 int count = sizeof(strStates) / sizeof(strStates[0]); int x = 0; printf("排序前的省份列表:\n"); for (x = 0; x < count; x++) { printf("%s\n", strStates[x]); } // 调用排序函数,传入数组和元素数量 sort(strStates, count); printf("\n按字母顺序排序后的省份列表:\n"); for (x = 0; x < count; x++) { printf("%s\n", strStates[x]); } return 0; }
内容的提问来源于stack exchange,提问作者Woody
相关产品推荐
相关产品推荐

