将字符串数组传递给函数分段错误

所以,我在下面编写了这个代码,它应该将一个字符串数组传递给一个函数,然后将该数组按字母顺序排序。 我知道我做的方式可能并不漂亮,但它适用于学校,我需要将它传递给函数并使用strcmp 。 我遇到了一些问题,但我设法将所有编译错误排序。 但是,现在,当我尝试运行程序时,我得到错误segmentation fault(core dumped) 。 有人能引导我到我犯错误的地方吗?

 #include #include #include #include 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  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]); } 

你不能覆盖strcpy()将要执行的字符串文字,修改字符串文字会调用未定义的行为,而是交换指针。

这个

 strcpy(alpha, str[y - 1]); strcpy(str[y - 1], str[y]); strcpy(str[y], alpha); 

会工作得很好

 alpha = str[y - 1]; str[y - 1] = str[y]; str[y] = alpha; 

如果你声明alpha

 char *alpha; 

另外,请注意字符串的大小不是11英寸

 char *states[11]; 

它是数组可以容纳的指针数。 指针指向字符串文字,在这种情况下,其大小并不重要。 重要的是数组包含指针,你可以将指针指向其他位置,但是你不能像字符串文字那样更改静态内存。

添加到iharob的答案,如果11中的状态中所有字符串的长度,则代码应该有效。当您尝试将“Oregon”与“California”交换时,代码会崩溃。 由于“California”的长度为11个字节,“Oregon”的长度为7个字节(包括空字符),当您使用strcpy用“California”覆盖字符串数组“Oregon”时,缓冲区溢出并且程序将核心转储信号11.您可以使用iharob建议的方法,或者您可以更改以下代码: –

 #include #include #include #include void sort(char str[][11]); int main() { char states[4][11] = {"Florida", "Oregon", "California", "Georgia"}; sort(states); return 0; } void sort(char str[][11]) { 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]); } 

产生的产出将是: -

 gaurav@ubuntu:~$ ./a.out The states, in order, are: California Florida Georgia Oregon