将字符串数组传递给函数分段错误 [英] Passing an array of strings to a function-segmentation fault

查看:83
本文介绍了将字符串数组传递给函数分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在下面编写了此代码,该代码应将字符串数组传递给函数,然后该函数将数组按字母顺序排序.我知道我做的方法可能并不漂亮,但这是在学校里,我需要将其传递给函数并使用 strcmp .我遇到了一些问题,但是我设法将所有编译错误归类.但是,现在,当我尝试运行程序时,出现错误 segmentation fault(核心转储).有人可以引导我到我犯错的地方吗?

So, I've written this code below that is supposed to pass an array of strings to a function, which then sorts the array into alphabetical order. I know the way I've done it probably isn't pretty, but it is for school and I'm required to pass it to a function and make use of strcmp. I ran into some problems, but I managed to get all the compile errors sorted. Now, however, when I try to run the program, I get the error segmentation fault(core dumped). Can someone guide me to where I made my mistake?

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

推荐答案

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

You can't overwrite string literals which is what strcpy() would be doing, modifying string literals invokes undefined behavior, instead swap the pointers.

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 in

Also, notice that the size of the strings is not 11 in

char *states[11];

这是数组可以容纳的指针数.指针指向字符串文字,在这种情况下其大小并不重要.重要的是数组包含指针,您可以使指针指向其他地方,但不能像字符串文字所占用的那样更改静态内存.

It's the number of pointers the array can hold. The pointers point to string literals, whose size is not really important in this case. The important thing is that the array contains pointers, and you can make pointers point somewhere else, but you can't change static memory like the one occupied by string literal.

这篇关于将字符串数组传递给函数分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆