Home > OS >  segmentation fault (core dumped) error when trying to copy from an array
segmentation fault (core dumped) error when trying to copy from an array

Time:06-04

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.

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

CodePudding user response:

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. (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)

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. If you whant to get length of a string it is better to use 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. ()

  • Related