在主函数中输入6个人的姓名(用二维数组定义),然后调用函数,把这6个人按名称拼音顺序排序,形参要用到指向一维数组的指针变量。然后在主函数中按序输出出来。
时间: 2023-04-23 09:03:51 浏览: 132
好的,下面是回复:
可以按照以下步骤实现:
1. 在主函数中定义一个二维数组,用来存储6个人的姓名,例如:char names[6][20] = {"张三", "李四", "王五", "赵六", "钱七", "孙八"};
2. 定义一个函数,用来对这6个人的姓名按照拼音顺序排序。函数的形参应该是一个指向一维数组的指针变量,例如:void sortNames(char (*names)[20]);
3. 在函数中使用字符串比较函数strcmp(),对姓名进行排序。可以使用冒泡排序或快速排序等算法。
4. 在主函数中调用sortNames()函数,将6个人的姓名按照拼音顺序排序。
5. 最后在主函数中按照顺序输出排序后的姓名,例如:for(int i=; i<6; i++) { printf("%s\n", names[i]); }
完整代码如下:
#include <stdio.h>
#include <string.h>
void sortNames(char (*names)[20]);
int main() {
char names[6][20] = {"张三", "李四", "王五", "赵六", "钱七", "孙八"};
sortNames(names);
for(int i=; i<6; i++) {
printf("%s\n", names[i]);
}
return ;
}
void sortNames(char (*names)[20]) {
char temp[20];
for(int i=; i<5; i++) {
for(int j=i+1; j<6; j++) {
if(strcmp(names[i], names[j]) > ) {
strcpy(temp, names[i]);
strcpy(names[i], names[j]);
strcpy(names[j], temp);
}
}
}
}
阅读全文
相关推荐










