Modify a char* string in C

前端 未结 6 1268
既然无缘
既然无缘 2021-01-27 23:32

I have this:

char* original = \"html content\";

And want to insert a new

char* mycontent = \"newhtmlinsert\";

6条回答
  •  礼貌的吻别
    2021-01-28 00:09

    Attempting to modify the contents of a string literal results in undefined behavior.

    You will need to allocate a target buffer (either as an auto variable or by using malloc) that's large enough to hold your final string plus a 0 terminator.

    Also, you might want to use sprintf to make life a little easier, such as

    sprintf(result, "%s before %s - %s - %s after %s", original, 
        tag, mycontent, original, tag);
    

提交回复
热议问题