如何在C中正确使用malloc?

问题描述 投票:-1回答:1

我正在编写一个程序,我想在其中找到所有丰富的数字,直到28124。我可以使用静态数组来实现,但是我想改善代码并以动态方式进行调整。这是我的代码

`

#define N 28124

bool is_abundant(int number)
{
    int i;
    int sum=0;
    for(i=1;i<=number/2;i++)
    {
        if(number % i == 0)
            sum += i;
        if(sum > number)    return true;
    }

    return false;
}

int main(int argc, char **argv)
{
    clock_t start = clock();

    int i, j=0;
    int *abundants = NULL;  

    for(i=12;i<N;i++)
    {
        if(is_abundant(i))
        {
            abundants = (int*)malloc(sizeof(int));
            assert(abundants);
            abundants[j] = i;
            j++;
        }
    }

    for(i=0;i<j;i++)
    {
        printf("%d ", abundants[i]);
    }

    clock_t end = clock();   
    double time = (double) (end - start)/CLOCKS_PER_SEC;
    printf("Execution time: %lf\n", time);
    return 0;
}

程序由于断言失败而中止,但是如何更改它以便以动态方式正常工作?

c memory dynamic allocation
1个回答
1
投票

您需要将sizeof(int)乘以要分配的整数数量。否则,您只分配一个元素。

您还需要使用realloc(),以便您扩展现有数组而不是分配新数组。

    for(i=12;i<N;i++)
    {
        if(is_abundant(i))
        {
            abundants = realloc(abundants, (j+1) * sizeof(int));
            assert(abundants);
            abundants[j] = i;
            j++;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.