扩展字符串而不连接

时间:2015-01-13 15:44:42

标签: c string memory-mapped-files

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


                            // 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  \0 \0 \0 \0 \0     /       O   v   e   r   f   l   o   w   \0

1 个答案:

答案 0 :(得分:1)

#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, '\0', 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;
}