在使用数组申请空间大小时,总是给定空间大小,如何在不给定空间大小的情况下自动获取键盘输入的字符串的内存空间大小
每次写入一个字符就对字符串使用realloc函数重新分配空间,这样就可以做到动态分配内存
#include <stdio.h>
int main()
{
int strLen = 5;
char ch;
char* str = (char*)malloc(sizeof(char*) * strLen);
int count = 0;
printf("Please input a string: ");
do
{
ch = getchar();
count++;
if (count >= strLen)
{
str = (char*)realloc(str, sizeof(char*) * (++strLen));
}
str[count-1] = ch;
}
while (ch != '\n');
str[count] = '\0';
puts(str);
return 0;
}