メモリから整数を保存して出力するプログラムを作成する必要があります。realloc を使用する必要があります。基本的に、プログラムは 2 int のサイズを割り当てます。入力に 2 つの int が与えられると、さらに 1 つの int のスペースを再割り当てし、double を出力する必要があります。次に、input に 3 つの int が与えられると、int にさらに 2 つのスペースを割り当て、double を出力する必要があります..など..
Test cases:
input file in.0:
------
4
------
expected output:
------
4
------
=================================================
input file in.1:
------
4 5
------
expected output:
------
4
5
double
------
==================================================
input file in.2:
------
4 5 3
------
expected output:
------
4
5
double
3
double
------
===================================================
input file in.3:
------
4 5 3 2 9
------
expected output:
------
4
5
double
3
double
2
9
double
このプログラムを書きましたが、メモリが適切に割り当てられません。誰かが私を書き込み方向に案内してもらえますか?
int main(void)
{
int c;
int digit;
int count = 0;
int d_size = 1;
int init_size = 2;
int *p = (int *) malloc(sizeof(int) * init_size);
while((c = scanf("%i", &digit)) != EOF)
{
if (c == 1)
{
*(p+count) = digit;
count++;
}
else
{
printf("not valid");
}
printf("%i\n", digit);
if (count >= 2)
{
printf("double\n");
p = (int *) realloc(p, sizeof(int) * d_size);
d_size = d_size * 2;
}
}