Linked Questions

Popular Questions

How to append a char at a defined position

Asked by At

I'm trying to add a character at a defined position. I've created a new function, allocate a memory for one more char, save characters after the position then added my character at the defined position, and now I don't know how to erase characters after that position to concatenate the saved string. Any solution?

Here is the beginning of my function:

void appendCharact(char *source, char carac, int position) {
    source = realloc(source, strlen(source) * sizeof(char) + 1); //Get enough memory
    char *temp = source.substr(position); //Save characters after my position
    source[position] = carac; //Add the character

EDIT : I'm trying to implement another "barbarous" solution, in debug mode I can see that I've approximately my new string but it look like I can't erase the older pointer...

void appendCharact(char *source, char carac, int position) {
    char *temp = (char *)malloc((strlen(source) + 2) * sizeof(char));
    int i;
    for(i = 0; i < position; i++) {
        temp[i] = source[i];

    temp[position] = carac;
    for (i = position; i < strlen(source); i++) {
        temp[i + 1] = source[i];
    temp[strlen(temp) + 1] = '\0';
    source = temp;

Related Questions