0

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

我希望我的解释足够清楚。如果没有,我可以尝试再次解释。

谢谢!:)

4

2 回答 2

1

你想imagine->data待多久?您似乎希望它是width长元素,所以这样做:

imagine = ( XPM* ) malloc ( sizeof ( XPM ) + sizeof ( unsigned int* ) * width);

此外,(XPM*)强制转换在 C 中是不必要的,但这并不重要。它不会阻止您的代码工作。

这是不必要和错误的:

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将与结构分开存储imagine

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

于 2014-02-27T00:02:02.960 回答
-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”数据数组的分配已经在第一组中分配。

于 2014-02-26T23:19:32.997 回答