0

メモリから整数を保存して出力するプログラムを作成する必要があります。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;
        }

    }
4

1 に答える 1

4

あなたinit_sizeは 2 ですが、あなたd_sizeは 1 です。まず、 を にd_size等しくしinit_sizeます。次に、実際にサイズを大きくするd_size = d_size * 2前に行う必要があります。realloc


補足:reallocメモリ不足の場合は失敗します。あなたが書く場合:

p = realloc(p, ...);

失敗した場合、以前に割り当てられたメモリが失われます。常にrealloc次のように使用する必要があります。

enlarged = realloc(p, ...);
if (enlarged == NULL)
    // handle error
else
    p = enlarged;

サイドノート2:ポインタのタイプを変更してしまう可能性があります。繰り返さないほうがいい。それ以外の

int *p;
p = (int *)malloc(sizeof(int) * count);

書きます:

int *p;
p = malloc(sizeof(*p) * count);
于 2012-06-27T18:58:17.737 に答える