C appending char to char*

前端 未结 5 965
一个人的身影
一个人的身影 2021-01-18 06:15

So I\'m trying to append a char to a char*.

For example I have char *word = \" \"; I also have char ch = \'x\';

5条回答
  •  心在旅途
    2021-01-18 06:50

    It is hard to append to a string in-place in C. Try something like this:

    char *append(const char *s, char c) {
        int len = strlen(s);
        char buf[len+2];
        strcpy(buf, s);
        buf[len] = c;
        buf[len + 1] = 0;
        return strdup(buf);
    }
    

    Be sure to deallocate the returned string when done with it.

    FYI: It segfaults probably because the string you are passing is stored in read-only memory. But you're right, you are also writing off of the end (the [len+1] write, not the [len] one).

提交回复
热议问题