C程序设计中的动态字符数组插入元素
在C编程中尝试向动态字符数组添加元素时遇到了一些问题。以下是预期输出:C程序设计中的动态字符数组插入元素,c,arrays,dynamic,char,C,Arrays,Dynamic,Char,在C编程中尝试向动态字符数组添加元素时遇到了一些问题。以下是预期输出: 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 我已经在mai
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
我已经在main函数中完成了这些用户输入部分,下面是main中的代码,在这里我接受字符串输入,调整大小并将它们传递给insert():
以及插入()的部分:
void插入(char*str,char输入,int n){
int i;
空间大小=1;
对于(i=0;i2){
打破
}
}
对于(i=0;i
但是,当我试图从insert()打印字符串时,假设我输入了'a'
以附加到动态数组的第一个大小为5的元素,得到的结果是abcd=
我从中引用了,我不确定如何修复此问题。提前感谢。您可以使用
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 */
}
并使用引用传递str
insert(&str, input, n); /* Note the '&' */
下面是代码-与合同,调用者做免费位!调用者使用
insert(&str,input,n)
很抱歉格式化。这就留给读者了。我没有检查算法,但这不会泄漏内存为什么人们不检查
scanf
的返回值?对不起,您的意思是检查作为参数从main传递到insert()的输入吗?我检查了一下,结果是正确的。例如,当我输入“b”时,输出变成bcde=。然后让我们假设q,outout变成了qrst=etc etc函数scanf
返回一个值-它有多成功。应进行检查,以确保相关变量已“填写”。人们输入错误,可能会给他们一个重新输入数据的机会(请阅读scanf
-为什么你要不断地将input+i
存储到str
缓冲区?既然input
是a
当然你会得到b
(a+1),c
(a+2),等等。为什么连续不断地realloc
?您确切地知道最后一个字符串需要多长。只需malloc
一次就可以了。这有一个内存泄漏是的。修复了它,还有一个bug。谢谢。不太修复-realloc
可以返回抛出的不同地址away@CoolGuy编号realloc()
无法神奇地更新指向str
的所有指针。感谢您复制我的答案。非常感谢!它很有效,也感谢您的解释!但简短的问题是,当您重新定位*str时,n增加了2。因此,我能假设1个空格用于新输入,而另一个空格用于'\0'吗?一个假设空字符在那里已经是e了。我们只需要移动它。所以+2可以是+1。我明白了。非常感谢你的帮助!
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 */
}
insert(&str, input, n); /* Note the '&' */
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 */
}