c - 为结构体中的灵活数组分配内存

标签 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);
        }
    }

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

谢谢! :)

最佳答案

您希望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/

相关文章:

c - 使用 malloc 时遇到问题

c++ - MicroBlaze 上 C++ 的线程安全

c - 在 linux 中使用 PF_PACKET 错误设置 IP_HDRINCL

java - 在我的字符数组中查找特殊字符的数量

java - 如何使用数组来存储问题和答案以进行测验

java - 使用另一个数组的大小初始化多维数组而不处理java中的元素

c - Malloc 结构指针错误

c - typedef 和 struct 的语法错误?

c - inotify IN_CLOSE_WRITE 仅检测复制到目录的文件

c - MLF 是一种公平的调度协议(protocol)吗?