This question already has answers here:
Closed 6 years ago.
Why do I get a segmentation fault when writing to a string initialized with “char *s” but not “char s[]”?
(17个答案)
我正试图用'G'替换'R',但出现未处理的异常。
int main()
{
    char *pszStr1 = "EFGH";

    (++pszStr1)[1] = 'R';

    printf("%s", pszStr1);
    return 0;
}

最佳答案

字符串位于只读区域。
相反,做

int main()
{
    static char pszStr1arr[] = "EFGH";
    char *pszStr1 = pszStr1arr;

    (++pszStr1)[1] = 'R';
    printf("%s", pszStr1);
    return 0;
}

关于c - 替换字符串中的字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18182855/

10-12 05:08