创建字符串所以我试图编写一个程序,基本上通过内存分配,每个字符读取字符,但只通过键盘输入一个字符串创建一个字符串。我知道有很多(更好)的方法可以做到,但我想通过这种特殊的方式来做到这一点! 下面的代码:通过malloc和getchar()
int newstring (char** string)
{
printf("--------------In function newstring--------------\n");
int i = 0;
string = malloc (sizeof (char));
printf("Adress: %p\n", (void*)string);
if (string == NULL)
return -1;
while (1)
{
printf("Pre-scan\n");
*(string[i]) = getchar();
printf("After-scan\nstring[%d] = %c\n", i, *(string[i]));
i++;
if (*(string[i-1]) == '\n')
break;
printf("Reallocation to size %d\n", i+1);
string = realloc (string, sizeof (char) * (i+1));
if (string == NULL)
return -1;
}
string[i-1] = '\0';
printf("--------------Exit function newstring--------------\n");
return;
}
int main()
{
char *string;
newstring (&string);
printf("%s\n", string);
}
的问题是,程序总是读第三个字符之前中途死机,这里所发生的printfs输出:
Adress: 00AE1578
Pre-scan
1st Input: >>Hello
After-scan
string[0] = H
Reallocation to size 2
Pre-scan
After-scan
string[1] = e
Reallocation to size 3
Pre-scan
我想知道,如果是因为缓冲区有一些限制,但我觉得很难相信这个限制是2个字符(我尝试了多个输入,总是在第三个字符之前卡住)。还试着用“scanf(”%c“,*(string [i]))”来得到相同的结果。
你永远不会调用'free' - 你的程序会泄漏内存并最终停止,因为它会耗尽内存。 – Dai
@Dai我不需要免费调用,因为realloc已经释放了以前分配的内存。如果你说我应该主要免费打电话,那么你是对的,但这个计划从来没有达到主要的,所以这不是问题! –
@ryyker我意识到这一点,我这样做是为了清晰(如果有人看到我的代码,他们会知道我为“char”数组分配内存) –