C语言用指针数组将4个字符串{"red","blue","yellow","green"}从小到大排序后输出
时间: 2024-04-23 20:20:25 浏览: 95
可以使用指针数组和字符串比较的方法来实现对字符串数组的排序。以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
void sortStrings(char *strings[], int n) {
char *temp;
int i, j;
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[] = {"red", "blue", "yellow", "green"};
int n = sizeof(strings) / sizeof(strings);
int i;
sortStrings(strings, n);
printf("排序后的字符串数组:\n");
for (i = 0; i < n; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
```
运行结果:
```
排序后的字符串数组:
blue
green
red
yellow
```
阅读全文