为另一个结构内的结构数组分配内存 [英] Allocating memory for a structure array inside another structure
问题描述
我真的不知道这里有什么问题.编译器说一切正常,但是当我运行它时,可执行文件崩溃了(我相信这是一个分段错误问题).都说两颗心总比一颗好,所以我希望你们能找到我遗漏的东西.
I really don't know what the issue is here. The compiler says it's all okay, but when I run it, the executable crashes ( I believe it's a segmentation fault problem ). They say two minds are always better than one, so I hope you guys can find whatever I have missed.
好的,所以它是这样的:我有两个结构:
Okay, so it goes this way: I have 2 structures:
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 数组分配内存(我不会在这里编写故障安全代码):
Then, in a function I allocate memory for the XPM structure and then for the Color array inside the XPM structure (I won't write the fail safe code here):
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 */
当我尝试访问颜色表中的字段时出现问题
The problem shows when I try accessing the fields in the Color table
imagine -> colta [ index ].r = r;
也许这只是我犯的一个小错误,但我找不到.有人有想法吗?
Maybe it's just a small mistake I made, but I cannot find it. Does anyone have an idea?
谢谢!:)
编辑
main 函数中到这个程度的代码是这样的:
The code in the main function to this extent is this:
XPM *img;
initXPM(img, 10, 10, 1, 3);
setXPMColor(img, 0, 255, 255, 255, "0");
setXPMColor 函数是这样的:
The setXPMColor function goes like this:
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 <stdio.h>
#include <stdlib.h>
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);
这篇关于为另一个结构内的结构数组分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!