如何复制字符串?

时间:2019-02-11 14:53:02

标签: c++ string

C函数将字符串复制到相同的字符串,但是将任何重复的字符':'替换为一个,但是为什么会有'Exception write access':

void shiftStr(char* str)
{
    int len = strlen(str);
    int c = 0;
    int n1 = 0;
    int j = 0;
    std::cout << "string0:" << str << "\n";
    for (int i = 0; i < len; i++)
    {
        if (str[i] == ':')
            n1++;
        else
            n1 = 0;
        if (n1 > 1)
            continue;

        str[j] = str[i];//<-----------Exception write access
        j++;
    }
    std::cout << "string1:" << str << "\n";
}

int main()
{
    char* str = (char*)"a:z::bb:::cc::::";
    shiftStr(str);
}

1 个答案:

答案 0 :(得分:3)

字符串文字是只读的。您正在将"a:z::bb:::cc::::"文字转换为(char*),这将隐藏您的错误。用const char *str = (const char *)"a:z::bb:::cc::::"替换该行,编译器会抱怨。

要解决此错误,请将字符串从只读内存移到堆栈:

char str[] = "a:z::bb:::cc::::" // The string literal is stored as an array on the stack (don't make it too big!)