动态数组C上的赋值无效

时间:2017-07-12 06:28:46

标签: c pointers malloc

你好我在C中创建一个程序,它在一个动态数组上存储整数,每次必须添加一个新元素时都使用realloc,我在main上声明数组:

array:3 [▼ "_token" => "YQgV3t1dc0GZrIdPboZvflBDxs7KXCEdcQkFDrD4" "username" => "boby" "password" => "1234" ]

int *abundants;

一旦完成,我想将修改后的数组传递给另一个函数进行其他计算

int count = abundant_numbers(&abundants);

第一次进入if语句没有问题,但第二次在作业中得到int abundant_numbers(int *abundants[]){ if (!(*abundants = (int*) malloc(sizeof(int)))){ perror("malloc error!\n"); exit(EXIT_FAILURE); } *abundants[0] = 12; //we know the very first abundant number int count = 1, n = 14; while (n < MAX_NUM){ if (is_abundant(n)) { if (!(*abundants = (int*) realloc(*abundants,(count+1) * sizeof(int)))){ perror("Error in realloc\n"); exit(EXIT_FAILURE); } *abundants[count] = n; count++; } n += 2; //no odd abundant numbers } return count; } ,当访问丰富[2]时,我不明白为什么它不是一个有效的位置,如果它对丰富的人来说工作得很好[1]

感谢。

2 个答案:

答案 0 :(得分:1)

你的问题很简单:

*abundants[0] = 12;

*abundants[count] = n;

索引运算符[]的优先级高于取消引用运算符*。所以在这里你直接将abundants视为数组指针并尝试取消引用该元素。你想要的是

(*abundants)[0] = 12;

(*abundants)[count] = n;

这可以解决您的问题,其余代码将正常工作。

话虽如此,我强烈建议使用这样的数据结构:

struct dynarr
{
    size_t count;
    size_t capacity;
    int entries[];
}

realloc()更大的块,总是在count到达capacity时。 realloc()代价很高,您可能会在典型的基于堆的实现中分割堆空间。您的代码可以查找如下示例:

#include <stdio.h>
#include <stdlib.h>

#define MAX_NUM 1024

int is_abundant(int x) { return x; } // simple fake to make it compile, replace

struct dynarr
{
    size_t count;
    size_t capacity;
    int entries[];
};

struct dynarr *createarr(size_t capacity)
{
    struct dynarr *arr = malloc(sizeof(*arr) + capacity * sizeof(int));
    if (!arr)
    {
        perror("malloc error!\n");
        exit(EXIT_FAILURE);
    }
    arr->count = 0;
    arr->capacity = capacity;
    return arr;
}

struct dynarr *expandarr(struct dynarr *arr)
{
    size_t capacity = arr->capacity * 2;
    struct dynarr *newarr = realloc(arr,
            sizeof(*newarr) + capacity * sizeof(int));
    if (!newarr)
    {
        perror("malloc error!\n");
        free(arr);
        exit(EXIT_FAILURE);
    }
    newarr->capacity = capacity;
    return newarr;
}

struct dynarr *abundant_numbers(void){
    struct dynarr *abundants = createarr(32);
    abundants->entries[abundants->count++] = 12; //we know the very first abundant number

    int n = 14;

    while (n < MAX_NUM){
        if (is_abundant(n)) {
            if (abundants->count == abundants->capacity)
            {
                abundants = expandarr(abundants);
            }
            abundants->entries[abundants->count++] = n;
        }
        n += 2;     //no odd abundant numbers
    }

    return abundants;
}

int main(void)
{
    struct dynarr *abundants = abundant_numbers();

    for (size_t i = 0; i < abundants->count; ++i)
    {
        printf("%d ", abundants->entries[i]);
    }
    free(abundants);
    putchar('\n');
}

答案 1 :(得分:0)

the biggest problem is that the code is expecting an array of pointers to int.

But the code is only producing an array of `int`s

And the code contains several 'magic' numbers (2, 12, 14)


int *abundants = NULL;

int count = abundant_numbers(&abundants);



int abundant_numbers(int *abundants[])
{

     if (!( abundants = malloc(sizeof(int))))
     {
         perror("malloc error!\n");
         exit(EXIT_FAILURE);
     } 

     abundants[0] = 12;     //we know the very first abundant number
     int count = 1;
     int n = 14;

     while (n < MAX_NUM)
     {
        if (is_abundant(n))
        {
            void *temp;
            if (!( temp = realloc(abundants,(count+1) * sizeof(int))))
            {
                perror("Error in realloc\n");
                free( abundants );
                exit(EXIT_FAILURE);
            }

            // implied else, realloc successful

            abundants = temp;
            abundants[count] = n;
            count++;
        }
        n += 2;     //no odd abundant numbers
    }

    return count;
}

但是,由于MAX_NUM是已知值, 最好在开始时分配那么多内存。

并强烈建议不要特殊的&#39;码 对于&#39; n&#39;。

的特殊情况

并提供魔法&#39;编号有意义的名字,通过#define陈述建议。

示例代码如下:

#include <stdlib.h>   // malloc(), free()

// use whatever value your program needs in the following statement.
#define MAX_NUM 1024
#define FIRST_ABUNDANT 12
#define STEP_AMOUNT 2

// prototypes
int abundant_numbers( int * );


int main( void )
{
     int *abundants = NULL;

     if (!( abundants = malloc(sizeof(int) * MAX_NUM)))
     {
         perror("malloc error!\n");
         exit(EXIT_FAILURE);
     } 

     // implied else, malloc successful

    int count = abundant_numbers( abundants  );
} // end function: main


int abundant_numbers( int *abundants )
{
     int count = 0;

     for( int n=FIRST_ABUNDANT; n < MAX_NUM; n+=STEP_AMOUNT )
     {
        if (is_abundant(n))
        {
            abundants[count] = n;
            count++;
        }
    }

    return count;
}  // end function: abundant_numbers