尝试打印出字符串指针后,在字符数组的前动态插入字符时我有一些困难。字符串指针打印怪异符号
参数* str是从我的主动态字符数组,而输入为执行插入后应追加到动态数组的第一个元件的单个字符()。
int main(){
//code snippet. I removed other part to keep the question short
printf("How many characters do you want to input: ");
scanf("%d", &n);
str = malloc(n + 1);
printf("Input the string class: ");
scanf("%s", str);
//switch statement
case '1':
printf("What is the character you want to 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;
for (i = 0; i < len; i++) {
printf("%c", new_str[i]);
}
}
当我试图通过new_str循环打印出字符串数组时,它给了我很奇怪的符号,我不知道它们是什么。有任何想法吗?
编辑
预期输出如下:
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
输出我得到:
'的strlen()'不计终止空。 –
那么我应该如何修改它?将for循环中的第二个条件更改为new_str [i]!='\ 0'? – hyperfkcb
也许'malloc(len + 2)'? –