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.
char* is how you declare a pointer to a char variable. It's useful when you want a string with unknown length.
StringBuilder. append(char c) method appends the string representation of the char argument to this sequence. The argument is appended to the contents of this sequence.
1. Using String. Insert a character at the beginning of the String using the + operator. Insert a character at the end of the String using the + operator.
Typical C practice would be like:
//returns 1 if failed, 0 if succeeded
int append(char*s, size_t size, char c) {
if(strlen(s) + 1 >= size) {
return 1;
}
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
return 0;
}
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 take char**
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With