Insert element into dynamic char array in C programming -
i having problem when trying add element dynamic char array in c programming. here expected output:
how many characters want input: 5 input string:datas string is: datas want 1-insert or 2-remove or 3-quit?: 1 character want insert: resulting string: adata
i did user input part in main function , here code in main take in string input, size , pass them insert():
printf("how many characters want input: "); scanf("%d", &n); str = malloc(n + 1); printf("input string class: "); scanf("%s", str); case '1': printf("what character want insert: "); scanf(" %c", &input); insert(str, input, n); break;
and part insert():
void insert(char *str, char input, int n) { int i; size_t space = 1; (i = 0; < n; i++) { str[i] = (char)(input + i); space++; str = realloc(str, space); if (i > 2) { break; } } (i = 0; < n; i++) { printf("%c", str[i]); } }
however, when tried print out string insert(), let's entered 'a'
append first element of dynamic array size of 5, result getting abcd=
i referenced stackoverflow thread , not sure how fix this. in advance.
here code - contract caller free bit! caller calls 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 malloc-ed memory */ exit(-1); /* exit program */ } (i = n; >= 0; i--) { (*str)[i + 1] = (*str)[i]; /* move characters */ } (*str)[0] = input; /* insert new character */ printf("%s", *str); /* print new string */ }
sorry formatting. left reader. have not checked algorithm not leak memory
Comments
Post a Comment