为另一个结构内的结构数组分配内存
我真的不知道这里的问题是什么。 编译器说它没关系,但是当我运行它时,可执行文件崩溃了(我相信这是一个分段错误问题)。 他们说两个人总是比一个人好,所以我希望你们能找到我错过的任何东西。
好的,所以就是这样:我有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 */
当我尝试访问Color表中的字段时,问题显示出来
imagine -> colta [ index ].r = r;
也许这只是我犯的一个小错误,但我找不到它。 有没有人有想法?
谢谢! 🙂
编辑
主要function中的代码就是这样:
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; }
void func(type *pointer){ //"type *pointer" : The only variable on the stack pointer = malloc(sizeof(type));//But is not set to the original. retrurn; }
简短的测试代码:
#include #include void init_int_pointer(int *p){ p = malloc(sizeof(*p)); } int main(){ int *p = NULL; printf("before : %p\n", (void*)p);//NULL init_int_pointer(p); printf("after : %p\n", (void*)p);//NULL return 0; }
修理
1) type * func(){ type *pointer = malloc(sizeof(type)); retrurn pointer; } ... type *p = func(); 2) void func(type **pointer){ *pointer = malloc(sizeof(type)); retrurn ; } ... type *p; func(&p);
你的sizeof
用法是错误的, sizeof ( imagine -> colta )
是指针的大小。
你的意思是:
imagine->colta = malloc(ncolors * sizeof *imagine->colta); ^ | important!
请注意星号,它表示“此指针指向的数据大小”,即sizeof (Color)
。
此外,确保分配实际上是成功的。
另外, 请不要在C中malloc()
的返回值 。
更新 :
您的问题似乎在于您如何调用初始化结构的函数; 你正在删除顶级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
应该return
本地的initXPM
变量,以便调用者获得该指针。