我正在尝试使用 flexarray 为结构分配内存。我以这种方式收到它,我必须像这样实现它。
结构如下:
struct _XPM {
unsigned int width;
unsigned int height;
unsigned char cpp;
unsigned int ncolors;
Color *colta;
unsigned int *data[];
}; //it's a typedef to XPM in the headder file
我有一个启动结构的函数。我有问题的地方就在那里。我真的不知道:我是否必须使用 malloc 为结构分配内存,仅此而已,还是我需要分配内存来*data[]
像指向数组的指针一样?
void initXPM(XPM *imagine,
unsigned int width,
unsigned int height,
unsigned char cpp,
unsigned int ncolors) {
imagine = ( XPM* ) malloc ( sizeof ( XPM ) + sizeof ( unsigned int* ) * width * height );
/* I think I need to allocate sizeof(unsigned int) *width * height because
I have to work with an array of pixels */
if(!imagine) {
perror( "Error allocating resources for XPM structure" );
exit(EXIT_FAILURE);
}
那么我是否必须编写以下代码?
imagine -> data = ( unsigned int* ) calloc( width, sizeof( unsigned int ) );
if( !imagine->data ) {
perror( "Error allocating resources for XPM data width" );
exit(EXIT_FAILURE);
}
for( i = 0; i < width; i++ ) {
imagine -> data[i] = (unsigned int*) calloc ( height, sizeof(unsigned int) );
if( !imagine -> data[i] ) {
perror( "Error allocating resources for XPM data height" );
exit(EXIT_FAILURE);
}
}
我希望我的解释足够清楚。如果没有,我可以尝试再次解释。
谢谢!:)