为结构中的灵活阵列分配内存

时间:2014-02-26 22:13:13

标签: c arrays malloc calloc flexible-array-member

我正在尝试使用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);
        }
    }

我希望我的解释足够明确。如果没有,我可以尝试再解释一下。

谢谢! :)

2 个答案:

答案 0 :(得分:1)

您希望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[];,那么这是正确的。如果您选择了这种方式,则需要为sizeof(XPM)而不是imagine分配sizeof(XPM) + sizeof(unsigned int*)*width字节,因为数组imagine->data将与结构{分开存储} { {1}}。

为每行像素分配数组的其余代码很好。

答案 1 :(得分:-1)

你应该做的就是做一些像:

XPM *initXPM(unsigned int width,
             unsigned int height,
             unsigned char cpp,
             unsigned int ncolors) {

    XPM *imagine = ( XPM* ) malloc ( sizeof ( XPM ) );
    imagine->data = ( unsigned int *) malloc ( sizeof ( unsigned int ) * width * height);

    if(!imagine) {
        perror( "Error allocating resources for XPM structure" );
        exit(EXIT_FAILURE);
    }

    ...

    return imagine;
}

不需要执行第二组语句,因为'unsigned int'数组的分配已经在第一组中分配。