【发布时间】:2015-06-24 00:32:22
【问题描述】:
所以,我在下面编写了这段代码,它应该将一个字符串数组传递给一个函数,然后该函数将数组按字母顺序排序。我知道我完成它的方式可能并不漂亮,但它是用于学校的,我需要将它传递给一个函数并使用strcmp。我遇到了一些问题,但我设法对所有编译错误进行了排序。但是,现在,当我尝试运行该程序时,我收到错误 segmentation fault(core dumped)。有人可以指导我到我犯错的地方吗?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
void sort(char *str[]);
int main()
{
char *states[11] = {"Florida", "Oregon", "California", "Georgia"};
sort(states);
return 0;
}
void sort(char *str[])
{
int x, y;
char alpha[11] = {0};
for(x = 1; x < 4; x++){
for(y = 1; y < 4; y++){
if(strcmp(str[y - 1], str[y]) > 0){
strcpy(alpha, str[y - 1]);
strcpy(str[y - 1], str[y]);
strcpy(str[y], alpha);
}
}
}
printf("\nThe states, in order, are: ");
for(x = 0; x < 4; x++)
printf("\n%s", str[x]);
}
【问题讨论】: