用指向指针的方法对5个字符串进行排序写一段c语言程序
时间: 2023-12-29 18:10:39 浏览: 40
下面是一个用指向指针的方法对5个字符串进行排序的C语言程序:
```c
#include <stdio.h>
#include <string.h>
void sort_strings(char **strings, int n) {
int i, j;
char *temp;
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (strcmp(strings[i], strings[j]) > 0) {
temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
}
}
}
int main() {
char *strings[] = {"hello", "world", "apple", "banana", "cherry"};
int n = 5;
int i;
printf("Before sorting:\n");
for (i = 0; i < n; i++) {
printf("%s\n", strings[i]);
}
sort_strings(strings, n);
printf("After sorting:\n");
for (i = 0; i < n; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
```
在这个程序中,我们使用了一个指向指针的指针 `char **strings` 来表示一个字符串数组。在 `sort_strings` 函数中,我们使用了两个循环来比较字符串并进行排序,最后返回一个按字母顺序排列的字符串数组。在 `main` 函数中,我们首先打印出排序前的字符串数组,然后使用 `sort_strings` 函数对其进行排序,并最后打印出排序后的字符串数组。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)