在C编程中将元素插入到动态字符数组中

Insert element into dynamic char array in C programming

我在 C 编程中尝试向动态字符数组添加元素时遇到了一些问题。这是预期的输出:

How many characters do you want to input: 5
Input the string:datas
The string is: datas
Do you want to 1-insert or 2-remove or 3-quit?: 1
What is the character you want to insert: a
Resulting string: adata

我已经在 main 函数中完成了那些用户输入部分,这里是 main 中的代码,我在其中接收字符串输入、大小并将它们传递给 insert():

printf("How many characters do you want to input: ");
scanf("%d", &n);
str = malloc(n + 1);
printf("Input the string class: ");
scanf("%s", str);

case '1':
    printf("What is the character you want to insert: ");
    scanf(" %c", &input);
    insert(str, input, n);
    break;

以及我的 insert() 所在的部分:

void insert(char *str, char input, int n) {
int i;
size_t space = 1;
for (i = 0; i < n; i++) {
    str[i] = (char)(input + i);
    space++;                       
    str = realloc(str, space); 
    if (i > 2) {
        break;
    }
}

for (i = 0; i < n; i++) {
    printf("%c", str[i]);
}
}

但是,当我尝试从 insert() 打印出字符串时,假设我输入 'a' 以附加到大小为 5 的动态数组的第一个元素,我得到的结果是 abcd=

我参考了 Whosebug thread 但我不确定如何解决这个问题。提前致谢。

您可以使用

void insert(char **str, char input, int n) {

    char* temp = *str;
    int i;

    *str = realloc(*str, n + 2); /* realloc first */

    if(!(*str)) /* realloc failed */
    {
        fputs("realloc failed", stderr);
        free(temp); /* Free the previously malloc-ed memory */
        exit(-1); /* Exit the program */
    }

    for (i = n; i >= 0; i--) {
        (*str)[i + 1] = (*str)[i]; /* Move all characters up */ 
    }

    **str = input; /* Insert the new character */

    printf("%s", *str); /* Print the new string */
}

并使用

通过引用传递str
insert(&str, input, n); /* Note the '&' */

这是代码 - 与调用者免费位的合同!调用者用 insert(&str, input, n)

调用它
void insert(char **str, char input, int n) {

char* temp = *str;
int i;

*str = realloc(*str, n + 2); /* realloc first */

if(!*str) /* realloc failed */
{
    fputs("realloc failed", stderr);
    free(temp); /* Free the previously malloc-ed memory */
    exit(-1); /* Exit the program */
}

for (i = n; i >= 0; i--) {
    (*str)[i + 1] = (*str)[i]; /* Move all characters up */ 
}

(*str)[0] = input; /* Insert the new character */

printf("%s", *str); /* Print the new string */
}

抱歉格式问题。那留给了reader。我没有检查算法但这不会泄漏内存