用指向指针的指针方法对字符串排序输出
时间: 2024-06-14 18:05:19 浏览: 13
以下是使用指向指针的指针方法对字符串进行排序并输出的示例代码:
```c
#include <stdio.h>
#include <string.h>
#define N 10
int main() {
char *str[5] = {"12", "11", "40", "35", "36"};
int i, j;
char **p, *t;
p = str;
for (i = 0; i < 4; i++) {
for (j = 0; j < 4 - i; j++) {
if (strcmp(*(p + j), *(p + j + 1)) > 0) {
t = *(p + j);
*(p + j) = *(p + j + 1);
*(p + j + 1) = t;
}
}
}
printf("输出结果:\n");
for (i = 0; i < 5; i++) {
printf("%s\n", str[i]);
}
}
```
这段代码使用了冒泡排序算法,通过比较字符串的大小来进行排序。在每一轮排序中,如果前一个字符串大于后一个字符串,则交换它们的位置。最终,字符串将按照升序排列。
相关问题
用指向指针的指针方法对5个字符串排序并输出
这里提供一种用指向指针的指针方法对5个字符串排序并输出的示例代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
void sortStrings(char** strings, int n) {
for (int i = ; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (strcmp(strings[i], strings[j]) > ) {
char* temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
}
}
}
int main() {
const int n = 5;
char* strings[n] = {"hello", "world", "apple", "banana", "orange"};
sortStrings(strings, n);
for (int i = ; i < n; i++) {
cout << strings[i] << endl;
}
return ;
}
```
这里定义了一个指向指针的指针 `char** strings`,它指向一个包含5个字符串的数组。在 `sortStrings` 函数中,使用了冒泡排序的方法对这5个字符串进行排序,最后在 `main` 函数中输出排序后的结果。
用指向指针的指针方法对五个字符串排序
要使用指向指针的指针方法对五个字符串进行排序,可以按照以下步骤进行:
1. 定义一个字符指针数组,用于存储五个字符串。
2. 定义一个指向指针的指针,用于指向字符指针数组的每个元素。
3. 使用冒泡排序等算法对指针数组进行排序,同时通过指向指针的指针来交换指针的位置,从而实现对字符串的排序。
4. 排序完成后,可以通过指向指针的指针依次访问每个字符串,进行后续的操作。
例如,以下是使用指向指针的指针方法对五个字符串进行排序的示例代码:
```c++
#include <stdio.h>
#include <string.h>
void sort(char **strings, int n) {
char *temp;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (strcmp(strings[j], strings[j+1]) > 0) {
temp = strings[j];
strings[j] = strings[j+1];
strings[j+1] = temp;
}
}
}
}
int main() {
char *strings[] = {"apple", "banana", "orange", "pear", "grape"};
char **ptr = strings;
sort(ptr, 5);
for (int i = 0; i < 5; i++) {
printf("%s\n", *(ptr+i));
}
return 0;
}
```
在这个示例代码中,使用了指向指针的指针 `char **ptr` 来指向字符指针数组 `char *strings[]` 中的每个元素,然后将指针数组传递给 `sort` 函数进行排序。排序完成后,可以通过指向指针的指针依次访问每个字符串,并打印输出。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)