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

时间:2015-10-10 10:14:04

标签: c arrays dynamic char

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

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的动态数组的第一个元素,我得到的结果是{ {1}}

我是从stackoverflow thread引用的,我不知道如何解决这个问题。提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用

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 '&' */

答案 1 :(得分:1)

这是代码 - 与调用者执行免费比特的合同!来电者使用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 */
}

抱歉格式化。这留给了读者。我没有检查算法,但这不会泄漏内存