Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C appending char to char*

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.

like image 416
Man Person Avatar asked Oct 17 '12 16:10

Man Person


People also ask

What is a char * in C?

char* is how you declare a pointer to a char variable. It's useful when you want a string with unknown length.

How do you append to a char?

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.

Can you add a char to a string?

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.


2 Answers

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.

like image 144
djechlin Avatar answered Oct 31 '22 08:10

djechlin


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).

like image 45
Keith Randall Avatar answered Oct 31 '22 06:10

Keith Randall