【问题标题】:Getting a 'segmentation fault' error when trying to use strcat to concatenate a char and a string [duplicate]尝试使用 strcat 连接字符和字符串时出现“分段错误”错误 [重复]
【发布时间】:2017-10-08 18:31:53
【问题描述】:

当我尝试访问字符串中的字符并将其添加到另一个字符串时,我不断收到此错误segmentation fault。代码如下。

提前致谢。

// function to find the initials of a name
void findInitials(char* name)
{
    char* initials = "";
    bool initialCreated = false;
    int n = 0;

    while(name[n] != '\0')
    {
        if(name[n] != ' ')
        {
            if(initialCreated == false)
            {
                //this is where I am facing the issue
                strcat(initials, &name[n]);
                printf("INITIAL: %c\n", name[n]);
                initialCreated = true;
            }

            if(name[n+1] == ' ')
            {
                initialCreated = false;
                n++;
            }
        }
        n++;
    }
}

【问题讨论】:

  • string 应该是什么?它不是 C 中的标准类型
  • 这看起来更像是一个糟糕的 C++,而不是 C。
  • 哎呀,我应该解决这个问题
  • 经验法则,将字符串写入未分配的内存是自找麻烦。

标签: c


【解决方案1】:

char* initials = ""; 不是char initials[SOME_SIZE] = {0}; 您没有分配任何内存,您只需获取一个指针并开始将一些字符写入内存,这些字符不应该被写入。一般来说,分段错误告诉您您正在修改一块您不允许修改的内存。这就是你的情况。

【讨论】:

    猜你喜欢
    • 2011-09-03
    • 2021-05-13
    • 1970-01-01
    • 2020-10-02
    • 2016-06-16
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    相关资源
    最近更新 更多