使用 Malloc() 使用指针创建整数数组

Using Malloc() to create an integer array using pointer

我正在尝试使用 malloc() 函数使用下面定义的 ADT 创建一个整数数组。我希望它 return 指向新分配的 intarr_t 类型整数数组的指针。如果它不起作用 - 我希望它成为 return 一个空指针。

这是我目前所拥有的 -

//The ADT structure

typedef struct {
  int* data;
  unsigned int len;
} intarr_t;

//the function 

intarr_t* intarr_create( unsigned int len ){

    intarr_t* ia = malloc(sizeof(intarr_t)*len);
    if (ia == 0 )
        {
            printf( "Warning: failed to allocate memory for an image structure\n" ); 
            return 0;
        }
    return ia;
}

我们系统的测试给我这个错误

intarr_create(): null pointer in the structure's data field
stderr 
(empty)

我到底哪里出错了?

从错误消息intarr_create(): null pointer in the structure's data field可以推断出每个结构的data个字段应该被分配。

intarr_t* intarr_create(size_t len){
    intarr_t* ia = malloc(sizeof(intarr_t) * len);
    size_t i;
    for(i = 0; i < len; i++)
    {
        // ia[len].len = 0; // You can initialise the len field if you want
        ia[len].data = malloc(sizeof(int) * 80); // 80 just for example
        if (ia[len].data == 0)
        {
            fputs("Warning: failed to allocate memory for an image structure", stderr); 
            return 0;
        }
    }
    return ia; // Check whether the return value is 0 in the caller function
}