【发布时间】:2015-10-10 20:38:45
【问题描述】:
在 char 数组的前面动态插入一个字符后尝试打印字符串指针时遇到了一些困难。
参数 *str 是我 main 中的一个动态字符数组,而输入是单个字符,它应该在执行 insert() 后附加到动态数组的第一个元素。
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' ?
-
strncpy() 是一个糟糕的函数,它确实不做大多数人一开始想的那样。最好不要使用它,或先阅读手册。在决定不使用它之前。
-
删除
insert(&str, input);中的& -
因为
&str是指向字符串的指针的地址,而不是字符串本身。