How to append a char at a defined position

  • A+
Category:Languages

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';     free(source);     source = temp; } 

 


Your new solution is much closer to a working function but it still has some problems:

  • you do not check for malloc() failure.
  • you should avoid computing the length of the source string multiple times.
  • temp[strlen(temp) + 1] = '/0'; is incorrect as temp is not yet a proper C string and strlen(temp) + 1 would point beyond the allocated block anyway, you should just write temp[i + 1] = '/0';
  • the newly allocated string should be returned to the caller, either as the return value or via a char ** argument.

Here is a corrected version:

char *insertCharact(char *source, char carac, size_t position) {     size_t i, len;     char *temp;      len = source ? strlen(source) : 0;     temp = (char *)malloc(len + 2);     if (temp != NULL) {         /* sanitize position */         if (position > len)             position = len;         /* copy initial portion */         for (i = 0; i < position; i++) {             temp[i] = source[i];         }         /* insert new character */         temp[i] = carac;         /* copy remainder of the source string if any */         for (; i < len; i++) {             temp[i + 1] = source[i];         }         /* set the null terminator */         temp[i + 1] = '/0';         free(source);     }     return temp; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: