我是 C 语言的初学者,我们在类里面有一个作业,需要获取给定的字符串列表,将它们放入字符串数组中,然后将其传递给用户定义的排序函数,该函数按字母顺序打印它们。每当我运行我的代码时,它都不会给出任何编译器错误,但它也会在运行时立即崩溃。调试给我一个段错误,但它没有给我导致它的特定行。我正在通过 Dev C++ 中包含的 gcc 编译器运行我的代码。 这是我的代码。任何帮助,将不胜感激。我认为我的问题是试图将一个字符串数组传递给该函数,但我无法找到关于该主题的任何我能理解的答案。
#include <stdio.h>
#include <string.h>
void sort(char *[]);
int main()
{
char *states[4] = {0};
states[0] = "Florida";
states[1] = "Oregon";
states[2] = "California";
states[3] = "Georgia";
sort(states);
return 0;
}
void sort(char *ptr[])
{
int i, j;
char temp[20];
for ( i = 1; i <= 4; i++ )
{
for ( j = 1; j <= 4; j++ )
{
if (strcmp(ptr[j-1], ptr[j]) > 0)
{
strcpy(temp, ptr[j-1]);
strcpy(ptr[j-1], ptr[j]);
strcpy(ptr[j], temp);
}
}
}
int x;
for ( x = 0; x < 4; x++ )
{
printf("%s", ptr[x]);
printf("\n");
}
}
最佳答案
我看到的问题:
您在
for
循环中使用了错误的索引。代替:
for ( i = 1; i <= 4; i++ ) { for ( j = 1; j <= 4; j++ )
使用:
for ( i = 0; i < 4; i++ ) // Keep the values in the range 0 - 3.
{
for ( j = 0; j < 4; j++ )
您正在修改只读内存。
当您使用时:
states[0] = "Florida";
states[0]
具有包含字符串"Florida"
的只读地址的值。如果您在sort
中修改该地址的值,您将进入未定义的行为领域。
您可以通过切换指针而不是复制值来解决问题。
// Use char* for temp instead of an array
char* temp;
if (strcmp(ptr[j-1], ptr[j]) > 0)
{
temp = ptr[j-1];
ptr[j-1] = ptr[j];
ptr[j] = temp;
}
附录,回应 OP 的评论
以下版本的 sort
适合我:
void sort(char *ptr[])
{
int i, j;
char* temp;
for ( i = 0; i < 4; i++ )
{
// NOTE:
// This is different from your version.
// This might fix your problem.
for ( j = i+1; j < 4; j++ )
{
if (strcmp(ptr[j-1], ptr[j]) > 0)
{
temp = ptr[j-1];
ptr[j-1] = ptr[j];
ptr[j] = temp;
}
}
}
for ( i = 0; i < 4; i++ )
{
printf("%s", ptr[i]);
printf("\n");
}
}
关于c - 如何将字符串数组传递给该程序中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29283029/