我正在尝试使用 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);
}
}
我希望我的解释足够清楚。如果没有的话我可以尝试再解释一下。
谢谢! :)
最佳答案
您希望imagine->data
有多长?看来您希望它的长度为 width
元素,所以这样做:
imagine = ( XPM* ) malloc ( sizeof ( XPM ) + sizeof ( unsigned int* ) * width);
此外,在 C 中,强制转换 (XPM*)
是不必要的,但这并不重要。它不会阻止您的代码运行。
这是不必要且错误的:
imagine -> data = ( unsigned int* ) calloc( width, sizeof( unsigned int ) );
if( !imagine->data ) {
perror( "Error allocating resources for XPM data width" );
exit(EXIT_FAILURE);
}
您已经在为 imagine->data
分配内存的同时为 imagine
本身分配了内存。如果您声明了 unsigned int **data;
而不是 unsigned int *data[];
,则这是正确的。如果您选择这种方式,则只需为 imagine
分配 sizeof(XPM)
字节,而不是 sizeof(XPM) + sizeof(unsigned int* )*width
,因为数组 imagine->data
将与结构 imagine
分开存储。
代码的其余部分(为每行像素分配一个数组)就可以了。
关于c - 为结构体中的灵活数组分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22054569/