我想創建一個整數數組,使用malloc()函數下面定義的ADT。我希望它返回一個指向新分配的intarr_t類型的整型數組的指針。如果它不起作用 - 我希望它返回一個空指針。使用Malloc()創建一個整數數組使用指針
這是我迄今爲止 -
//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)
哪裏abouts我已經錯了這裏?
我認爲目的是動態地爲結構中的* member *'data'分配內存。 –
您正在爲一堆'intarr_t'元素分配空間......但是如何爲每個元素中的「int * data」字段分配空間?那麼初始化每個元素的所有字段呢? – paulsm4
我該怎麼做呢?我不是很熟悉使用malloc和typedefs。 =/ –