【问题标题】:Segmentation fault when sorting an array of strings when using strcpy in c code在 c 代码中使用 strcpy 对字符串数组进行排序时出现分段错误
【发布时间】:2014-06-10 16:27:18
【问题描述】:

我正在尝试对字符串数组进行排序。如果我删除该行

strcpy(a[j-1],a[j]);

终端不会崩溃。

字符串数组以这种方式分配,以防出现问题

array=(char **)malloc(sizeof(char *)*N);

    for(i=0;i<N;i++)
        array[i]=(char *)malloc(sizeof(char)*6);

排序功能

void bubblesort1(char **a,int K)
{
    int i,j;
    char temp[6];

    for(i=1; i<K; i++)
        for(j=(K-1); j>=i; j--)
        {
            if(strcmp(a[j],a[j-1])>0)
            {
                strcpy(temp,a[j-1]);
                strcpy(a[j-1],a[j]);
                strcpy(a[j],temp);

            }

        }

}

为什么我会崩溃?

【问题讨论】:

  • 你确定没有一个字符串有长度&gt;5
  • 如果一个字符串有 6 个字符,比如“dancer”,那么你需要 7 个字节,因为一个字节需要保存空 (0) 终止符。
  • 好像是这样...谢谢
  • 有了你的数据布局,你不需要用strcpy复制字符串的内容;交换指向 char 的指针就足够了。
  • 如何将数据读入a的元素所指的内容?

标签: c string sorting crash strcpy


【解决方案1】:

确保在处理字符串时为空终止符允许一个额外的字节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-03
    • 2019-03-19
    • 2017-05-03
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    相关资源
    最近更新 更多