我正在尝试使用malloc()函数使用下面定义的ADT创建一个整数数组。我希望它返回一个指向新分配的intarr_t类型的整数数组的指针。如果它不起作用-我希望它返回一个空指针。
到目前为止,这就是我所拥有的-
//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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句