#include <stdio.h> #include <string.h> int swap(int s,int t); int main() { int ret; char a[5][100],*s,*t; int (*p)(int,int); s = a[0]; for (int i=0;i<5;i++) { scanf("%s",a[i]); } for (int i=1;i<5;i++) { t=a[i]; ret=strcmp(s, t); if(ret<0) { p=swap; (*p)(*s,*t); } } printf("%d\0",a[0]); printf("%d\0",a[1]); printf("%d\0",a[2]); printf("%d\0",a[3]); printf("%d\0",a[4]); return 0; } void swap(int*s,int*t) { int n=*t; *t=*s; *s=n; }这串代码怎么修改
时间: 2024-01-12 21:03:47 浏览: 126
这段代码有一些错误。首先,在`swap`函数中,参数`s`和`t`应该是指针类型。其次,在调用`swap`函数时,应该传递`s`和`t`的地址,而不是它们的值。此外,在最后输出结果时,应该使用`%s`格式化字符串而不是`%d`。最后,排序算法的实现也有误,应该使用冒泡排序或快速排序等算法来实现。
以下是修改后的代码:
```
#include <stdio.h>
#include <string.h>
void swap(char *s, char *t);
void bubble_sort(char arr[][100], int len);
int main() {
char a[5][100];
for (int i = 0; i < 5; i++) {
scanf("%s", a[i]);
}
bubble_sort(a, 5);
printf("%s\n", a[0]);
printf("%s\n", a[1]);
printf("%s\n", a[2]);
printf("%s\n", a[3]);
printf("%s\n", a[4]);
return 0;
}
void swap(char* s, char* t) {
char temp[100];
strcpy(temp, s);
strcpy(s, t);
strcpy(t, temp);
}
void bubble_sort(char arr[][100], int len) {
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (strcmp(arr[j], arr[j + 1]) > 0) {
swap(arr[j], arr[j + 1]);
}
}
}
}
```
修改后的代码中,我们将`swap`函数的参数类型改为了指针类型,并在`swap`函数和排序算法中使用了字符串比较函数`strcmp`来比较字符串大小。排序算法使用了冒泡排序算法来对字符串数组进行排序。最后,我们使用`%s`格式化字符串来输出排序后的结果。
阅读全文
相关推荐


















