c - 为另一个结构中的结构数组分配内存

标签 c pointers structure

我真的不知道这里有什么问题。编译器说一切正常,但是当我运行它时,可执行文件崩溃了(我相信这是一个段错误问题)。他们说两个想法总是比一个好,所以我希望你们能找到我遗漏的东西。

好的,事情是这样的:我有 2 个结构:

struct _Color {

    unsigned char r,g,b;
    char *pchars;
}; //typedef to Color in header file

struct _XPM {

    unsigned int width;
    unsigned int height;
    unsigned char cpp; 
    unsigned int ncolors;
    Color *colta; //collor table
    unsigned int *data[];

}; //typedef to XPM in header file

然后,在一个函数中,我为 XPM 结构分配内存,然后为 XPM 结构内的 Color 数组分配内存(我不会在这里编写故障安全代码):

XPM *imagine; //received as a parameter
imagine = ( XPM* ) malloc ( sizeof ( XPM ) + sizeof ( unsigned int* ) * width );
imagine -> colta = malloc ( ncolors * sizeof ( imagine -> colta ) ); 
/*I tried with both *imagine ->colta and imagine -> colta just to be safe */

当我尝试访问颜色表中的字段时出现问题

imagine -> colta [ index ].r = r;

也许这只是我犯的一个小错误,但我找不到它。有人有想法吗?

谢谢! :)

编辑

达到这个程度的main函数中的代码是这样的:

XPM *img;
initXPM(img, 10, 10, 1, 3);
setXPMColor(img, 0, 255, 255, 255, "0");

setXPMColor 函数是这样的:

void setXPMColor(XPM *imagine,
    unsigned int index,
    unsigned char r,
    unsigned char g,
    unsigned char b,
    char *charpattern) {


   imagine -> colta [ index ].r = r;
   imagine -> colta [ index ].g = g;
   imagine -> colta [ index ].b = b;
   imagine -> colta [ index ].pchars = charpattern;
}

最佳答案

你的sizeof用法是错误的,sizeof (imagine -> colta)是指针的大小。

你的意思是:

imagine->colta = malloc(ncolors * sizeof *imagine->colta);
                                         ^
                                         |
                                    important!

请注意星号,这意味着“该指针指向的数据的大小”,即 sizeof (Color)

当然,还要确保分配确实成功。

此外,please don't cast the return value of malloc() in C .

更新:

您的问题似乎在于如何调用初始化结构的函数;您正在删除顶级 malloc()ed XPM 指针:

XPM *img;
initXPM(img, 10, 10, 1, 3);
setXPMColor(img, 0, 255, 255, 255, "0");

应该是这样的:

XPM *img = initXPM(10, 10, 1, 3);
setXPMColor(img, 0, 255, 255, 255, "0");

当然 initXPM 应该返回本地 imagine 变量,以便调用者获得该指针。

关于c - 为另一个结构中的结构数组分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22068304/

相关文章:

使用指针将数据从一个地址复制到另一个地址

arrays - Matlab:连接两个元胞数组或结构

c - 为什么此 typedef 代码不创建实例

C - 使用动态数组复制结构

c - 双数组Trie的一种实现

android - 指针取消引用以访问另一个文件中的数组

c - 防止控制台窗口在 Visual Studio C/C++ 控制台应用程序上关闭

c - 引用指向结构体的指针,该结构体包含指向结构体指针的指针

c - 将文件中的信息写入存档文件?

c - 如何按名称杀死进程? (Win32 API)