0

I was having some problem when trying to add element to dynamic char array in C programming. Here is the expected output:

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

I already did those user input part in the main function and here is the code in main where I take in the string input, size and pass them to 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;

And the part where my 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]);
}
}

However, when I tried to print out the string from insert(), let's say I entered 'a' to append to the first element of dynamic array with a size of 5, the result that I am getting is abcd=

I referenced from the stackoverflow thread and I not sure how to fix this. Thanks in advance.

6
  • Why do people not check the return value of scanf? Commented Oct 10, 2015 at 10:16
  • Sorry but do you mean checking the input passing as parameter from main to insert()? I checked it and it was correct. Just that for example when I entered 'b', the output became bcde=. Then let's say q, the outout became qrst= etc etc Commented Oct 10, 2015 at 10:19
  • The function scanf returns a value - how successful it is. This should be checked to ensure that the relevant variable has been "filled in". People make typos and perhaps give them an opportunity to re-enter the data Commented Oct 10, 2015 at 10:21
  • (please read the manual page for scanf - linux.die.net/man/3/scanf Commented Oct 10, 2015 at 10:22
  • Why are you continuously storing input+i into the str buffer? Since input is a of course you then get b (a+1), c (a+2), etc. And why continuously realloc? You know exactly how long the final string needs to be. Just malloc once and be done with it. Commented Oct 10, 2015 at 10:22

2 Answers 2

1

Here is the code - with the contract that the caller does the free bit! The caller calls it with 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 */
}

Sorry about the formatting. That is left to the reader. I have not checked the algorithm but this does not leak memory

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot! It works and thanks for the explanation too!
But short question, when you realloc the *str, the n is increase by 2. So can I assume that 1 space is for the new input whereas the other is for the '\0'?
One assumes that the null character is there already. We just need to shift it. So the +2 could be +1
I see I see. Thanks a lot for the helps!
1

You can use

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 */
}

And pass str by reference using

insert(&str, input, n); /* Note the '&' */

8 Comments

This has a memory leak
Yes. Fixed it and also a bug. Thanks.
Not quite fixed - realloc can return a different address that is thrown away
@CoolGuy No. realloc() cannot magically update all pointers to str.
@FUZxxl, Ed Heal, Fixed. Thanks!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.