追加人物到字符数组在C [英] Appending Character to Character Array In C
本文介绍了追加人物到字符数组在C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要追加一个字符一个字符数组,重新presents的String。
我使用的是结构来重新present字符串。
结构字符串
{
字符* C;
INT长;
INT最大长度;}串;
的realloc 是搞乱我的数组;当我打印我的字符串,它从内存中打印随机的东西。
我觉得我做的realloc失去了参考我的字符串。
无效appendChar(字符串*目标,焦三)
{
的printf(\\字符串:%S \\ n,靶子> C); //正确打印字符串。 INT newSize =靶子>长度+ 1;
靶子>长度= newSize; 如果(newSize>&靶子GT;最大长度)
{
//销毁我的字符串。
靶子> C =(的char *)realloc的(目标,newSize *的sizeof(字符));
靶子>最大长度= newSize;
}
靶子> C [newSize-1] = CH;
靶子> C [newSize] ='\\ 0'; 的printf(字符串:%S \\ n,靶子> C);
}
解决方案
你对你的整体结构apllying realloc的目标
,你应该做的:
靶子> C =(字符*)的realloc(靶子&℃,newSize *的sizeof(字符));
I want to Append a character to a character array which represents a String. I am using a Struct to represent the String.
struct String
{
char *c;
int length;
int maxLength;
}String;
realloc is messing up my array; when I print my string, it prints random things from memory. I feel that I am losing the reference to my string by doing realloc.
void appendChar(String *target, char c)
{
printf("\String: %s\n", target->c); // Prints the String correctly.
int newSize = target->length + 1;
target->length = newSize;
if(newSize > target->maxLength)
{
// Destroys my String.
target->c= (char*) realloc (target, newSize * sizeof(char));
target->maxLength = newSize;
}
target->c[newSize-1] = ch;
target->c[newSize] = '\0';
printf("String: %s\n", target->c);
}
解决方案
You're apllying realloc on your whole structure target
, you should do :
target->c= (char*) realloc (target->c, newSize * sizeof(char));
这篇关于追加人物到字符数组在C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文