简体   繁体   English

尝试从数组复制时出现分段错误(核心转储)错误

[英]segmentation fault (core dumped) error when trying to copy from an array

trying to copy stuff from b into a but i get that error someone told me it means i'm trying to access memory that i'm not allowed to, but i don't know what should i do to make it compile.试图将东西从 b 复制到 a 但我收到有人告诉我的错误,这意味着我正在尝试访问我不允许的内存,但我不知道我应该怎么做才能使其编译。

replace(txt , code);

string replace(string a , string b)
{
    string alpha[26] = {"abcdefghijklmnopqurstuvwxyz"};

    for (int i = 0; i < strlen(a); i++)
    {
        for(int n = 0; n < 26; n++)
        {
            if(a[i] == alpha[n])
            {
                a[i] = b[n];
                i++;
            }
        }
    }
    return word;
}

i'm a beginner so no comments about clean coding or syntactic sugar or stuff like that just help me resolve this please我是初学者,所以请不要对干净的编码或语法糖或类似的东西发表评论,这只能帮助我解决这个问题

It looks like you have some problems with understending pointers , so I recommend you to read about them.看起来你在理解指针方面有一些问题,所以我建议你阅读它们。 Also consider reading about datatypes and types from STL you are using .还可以考虑阅读您正在使用的 STL 中的数据类型和类型。 (cause std::string is already an array of values so, when you are creating std::string[26], you actually are creating pointer to a pointer) (因为 std::string 已经是一个值数组,所以当您创建 std::string[26] 时,实际上是在创建指向指针的指针)

I guess you have are trying to do something like that:我猜你正在尝试做这样的事情:

std::string replace(string a , string b)
{
    std::string alpha = {"abcdefghijklmnopqurstuvwxyz"};

    for (size_t i = 0; i < a.size(); ++i)
    {
        for(size_t n = 0; n < alpha.size(); ++n)
        {
            if(a[i] == alpha[n])
            {
                a[i] = b[n];
                i++; // Also, I think you doesnt need this line, cause you already incrementing i in for loop
            }
        }
    }
    return a;
}

Also you have used strlen() on your string, that also is not really correct, cause it is used on char values.此外,您在字符串上使用了strlen() ,这也不是真正正确的,因为它用于 char 值。 If you whant to get length of a string it is better to use string.lenght()如果您想获取字符串的长度,最好使用string.lenght()

Also, It is better to use size_t or unsigned int instead of int in this case, cause you don't need negative numbers in order to parce these strings.此外,在这种情况下,最好使用size_tunsigned int而不是int ,因为您不需要负数来分割这些字符串。 () ()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM