【发布时间】:2018-02-05 20:24:43
【问题描述】:
我编写了以下代码来获取二维字符数组中的排序字符串
#include <stdio.h>
#include <string.h>
void swap(char *,char *);
void main() {
char a[20][20];
int Pass = 0, i = 0, j = 0, n;
printf("\nHow many elements you want to sort ? >> ");
scanf("%d", &n);
printf("\n\nEnter the elements to be sorted :\n");
for (i = 0; i < n; i++)
scanf("%s", a[i]);
for (Pass = 1; Pass < n; Pass++) {
for (j = 0; j < n - Pass; j++)
if (strcmp(a[j], a[j + 1]) < 0)
swap(a[j], a[j + 1]);
printf("\n\nPass = %d\n", Pass);
for (i = 0; i < n; i++)
printf(" %s ", a[i]);
}
}
void swap(char *a, char *b) {
char *t;
*t = *a;
*a = *b;
*b = *t;
}
但是,我得到的输出是
How many elements you want to sort ? >> 5
Enter the elements to be sorted :
1 2 3 4 5
Pass = 1
2 3 4 5 1
Pass = 2
3 4 5 2 1
Pass = 3
4 5 3 2 1
Pass = 4
Segmentation fault (core dumped)
为什么会遇到分段错误? (如果我使用整数数组而不是字符数组,相同的代码可以正常工作)
【问题讨论】:
-
main 必须返回
int -
您的
swap函数错误。 1)char *t; *t=*a;:使用未初始化的变量。 2)应该交换的是一个数组而不是一个指针(或一个char)。 -
节省时间,启用所有编译器警告:
char *t; *t=*a;应该在初始化之前警告t。 -
感谢@BLUEPIXY 指出,我通过 't=(char)malloc(20);' 为 t 分配了内存它奏效了
标签: c string char bubble-sort