我的意思是說,比如要輸入一個不定長的數組(或者是字符串),提示用戶輸入完後以某個字符或者標志結束,這個要怎麼實現啊?
用 realloc() ,下面是實現代碼作參考
#include <stdio.h>
#include <malloc.h>
int main(void)
{
char *p = NULL, *p1 = NULL, c;
int count = 0, i = 0, size = 100;
if(!(p = (char *)malloc(size)))
return 0;
while('0' != (c = getchar()))
{
if(count < 100)
{
p[i] = c;
}
else
{
size += 100;
p1 = (char *)realloc(p, size);
if(!p1)
{
break;
}
else
{
p = p1;
}
p[i] = c;
count = 0;
}
count++;
i++;
}
free(p);
return 0;
}