String pointer in C prints weird symbol -


i having difficulties when trying print out string pointer after dynamically insert character @ front of char array.

the parameter *str dynamic char array main whereas input single character should append first element of dynamic array after executing insert().

int main(){  //code snippet. removed other part keep question short printf("how many characters want input: "); scanf("%d", &n); str = malloc(n + 1); printf("input string class: "); scanf("%s", str);  //switch statement case '1':     printf("what character want insert: ");     scanf(" %c", &input);     insert(&str, input);     break; } return 0; }  void insert(char *str, char input) {     char *new_str;     int i, len = strlen(str);      new_str = malloc(len + 1);     new_str[0] = input;     strncpy(&new_str[1], str, len - 1);     new_str[len] = 0;      (i = 0; < len; i++) {         printf("%c", new_str[i]);     } } 

when tried loop thru new_str , print out string array, gives me weird symbols , have no idea they. ideas?

edit

the expected output below:

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 

the output getting:

enter image description here

alternative version, avoiding string copy functions. (since, alter strlen() know string length copy, don't need more string functions)

char * insert_a_character(char * str, char ch) { char * new; size_t len;  if (!str) return null; len = strlen(str);  new = malloc (1+len+1); if (!new) retun null;  new[0] = ch; memcpy(new+1, str, len); new[len+1] = 0;  return new; } 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -