插入元素插入C编程动态字符数组 [英] Insert element into dynamic char array in C programming
问题描述
我试图元素添加到C编程动态字符数组时,有一些问题。这里是预期的输出结果:
I was having some problem when trying to add element to dynamic char array in C programming. Here is the expected output:
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
我已经做在主要功能的用户输入部分,这里是主的code,我走在字符串输入,大小,并通过他们来插入():
I already did those user input part in the main function and here is the code in main where I take in the string input, size and pass them to insert():
printf("How many characters do you want to input: ");
scanf("%d", &n);
str = malloc(n + 1);
printf("Input the string class: ");
scanf("%s", str);
case '1':
printf("What is the character you want to insert: ");
scanf(" %c", &input);
insert(str, input, n);
break;
和部分在我的插入():
And the part where my insert():
void insert(char *str, char input, int n) {
int i;
size_t space = 1;
for (i = 0; i < n; i++) {
str[i] = (char)(input + i);
space++;
str = realloc(str, space);
if (i > 2) {
break;
}
}
for (i = 0; i < n; i++) {
printf("%c", str[i]);
}
}
然而,当我试图打印出从插入()的字符串,比方说我进入'A'
将追加到动态数组的一个尺寸的第一要素5,那我得到的结果是 ABCD =
However, when I tried to print out the string from insert(), let's say I entered 'a'
to append to the first element of dynamic array with a size of 5, the result that I am getting is abcd=
我从<引用href=\"http://stackoverflow.com/questions/5905379/how-would-you-add-chars-to-an-array-dynamically-without-the-array-being-$p$pdefi\">stackoverflow螺纹,我不知道如何解决这个问题。先谢谢了。
I referenced from the stackoverflow thread and I not sure how to fix this. Thanks in advance.
推荐答案
下面是code - 与主叫方的自由位合同!主叫方与称它为插入(安培; STR,输入,N)
Here is the code - with the contract that the caller does the free bit! The caller calls it with 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 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 */
}
很抱歉的格式。是留给读者。我没有检查的算法,但是这并不能泄漏内存
Sorry about the formatting. That is left to the reader. I have not checked the algorithm but this does not leak memory
这篇关于插入元素插入C编程动态字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!