在没有连接的情况下扩展字符串

Expanding string without concatenation

如何在不声明任何其他字符串的情况下扩展字符串以便将它们与源字符串连接起来?


                            // Figuratively clarification:

char *string = malloc(16);
strcpy(string, "Stack / Overflow");
&string[5] = expand(5);

                                 // Result (In-memory):

Idx: 0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21
Chr: S  t  a  c  k  [=10=] [=10=] [=10=] [=10=] [=10=]     /       O   v   e   r   f   l   o   w   [=10=]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *expand(char *s, int index, int size){
    size_t new_size = strlen(s) + size + 1;
    char *temp = realloc(s, new_size);
    if(temp == NULL){
        fprintf(stderr, "realloc error!\n");
        free(s);
        exit(EXIT_FAILURE);
    }
    s = temp;
    memmove(s + index + size, s + index, strlen(s + index)+1);
    memset(s + index, '[=10=]', size);
    return s;
}

int main(void) {
    char *sentence = "Stack / Overflow";
    char *string = malloc(strlen(sentence) + 1);
    int i;

    strcpy(string, sentence);
    string = expand(string, 5, 5);
    printf("Idx: ");
    for(i=0; i <= 21; ++i)
        printf("%3d", i);

    printf("\nChr: ");
    for(i=0; i <= 21; ++i){
        if(string[i])
            printf("%3c", string[i]);
        else
            printf("%3s", "\0");
    }
    printf("\n");
    free(string);
    return 0;
}