如何在C中正确使用malloc?

How to use malloc properly in C?

我正在编写一个程序,我想在其中找到 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;
    }

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

您需要将 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++;
        }
    }