So I’m trying to append a char to a char*.
For example I have char *word = " ";
I also have char ch = 'x';
I do append(word, ch); Using this method..
void append(char* s, char c)
{
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
It gives me a segmentation fault, and I understand why I suppose. Because s[len] is out of bounds. How do I make it so it works? I need to clear the char* a lot as well, if I were to use something like char word[500]; How would I clear that once it has some characters appended to it? Would the strlen of it always be 500? Thanks in advance.
Typical C practice would be like:
When passing a function an array to modify the function has no idea at compile time how much space it has. Usual practice in C is to also pass the length of the array, and the function will trust this bound and fail if it can’t do its work in the space it has. Another option is to reallocate and return the new array, you would need to return
char*or takechar**as an input but you must think carefully of how to manage heap memory in this situation. But without reallocating, yes, your function must somehow fail if it is asked to append when there is no space left, it’s up for you for how to fail.