C appending char to char*

前端 未结 5 991
一个人的身影
一个人的身影 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:47

    You can't really safely append to an arbitrary string, because firstly, string constants tend to be in read-only memory, so trying to write to them is likely to result in a segmentation fault, and secondly, you have no guarantee that if they've passed you a buffer that you haven't shot over the end of it.

    In particular, if you do char x[500];

    there's no guarantee that strlen(x) will return you 500. It will return you how many characters it has to count forward from the start of x before it reaches a null. It could return you 0, 1 ... 500, 501 ..., depending on what is in x.

    Really your only options are to call append with the size of the buffer you are appending to (so you can do something appropriate if the buffer is full), or to make append allocate a new buffer every time it is called, in which case you will need to free the buffer again of course.

提交回复
热议问题