【发布时间】:2015-05-03 06:18:43
【问题描述】:
我正在努力为 XPM 图像分配内存。
我用以下函数创建了自己的库:
XPM* initXPM (
unsigned int width,
unsigned int height,
unsigned int cpp,
unsigned int ncolors )
{
XPM *image;
image=(XPM*)malloc(sizeof(Color*) * (width * height) * cpp);
(*image).colta = (Color*) malloc(ncolors * sizeof(Color));
(*image).width = width;
(*image).height = height;
(*image).cpp = cpp;
(*image).ncolors = ncolors;
int i;
for (i = 0; i < ncolors; i++)
{
(*image).colta[i].pchars = (char*) malloc((cpp + 1) * sizeof(char));
}
(*image).data = (unsigned int**)malloc(height * sizeof(unsigned int*));
for (i = 0; i < height; i++)
{
(*image).data[i] = (unsigned int*) malloc(width * sizeof(unsigned int));
}
printf("init :height : %d , width :%d ncolors:%d , cpp : %d\n",(*image).height,(*image).width,(*image).ncolors,(*image).cpp);
return image;
}
XPM 结构如下所示:
typedef struct
{
unsigned int r,g,b; /* the red, green and blue components */
char *pchars; /* pointer to the character(s) combination */
} Color;
/* the number of characters for one color is contained into the XPM structure */
typedef struct
{
unsigned int width; /* width in pixels */
unsigned int height;
unsigned int cpp; /* number of characters per pixel */
unsigned int ncolors; /* how many colors we'll be using */
Color *colta; /* colors array */
unsigned int **data; /* the area that contains the image, */
/* width x height locations for */
/* indices into colta */
} XPM;
我是这样调用init函数的:
XPM *image;
image = initXPM(200,200,1,2);
我已成功使用值初始化 XPM 文件:(50,50,2,50)。如果我尝试使用 200 而不是 50 初始化文件,它会崩溃。
我想创建一个 200x200 XPM 文件,但它中断了。使用电子围栏我发现当我设置图像的宽度时它会崩溃。
我应该如何分配内存以便能够像这样使用它?
我尝试对结构进行一些修改,如果我在 main 方法中静态声明结构并将 XPM 图像的地址发送到 init 函数,它就可以工作,但我希望能够像库一样使用它。
【问题讨论】:
-
(*image).colta- nooooo! 只需image->colta。还有don't cast the return value ofmalloc(). -
我试过用
image->而不是(*image).,但结果是一样的 -
image=(XPM*)malloc(sizeof(Color*) * (width * height) * cpp)行非常可疑,因为您在其中的任何地方都没有使用sizeof(XPM)。 -
@Bogdan 是的,是一样的,只是
->更具可读性(这就是为什么我没有将其作为答案发布,而是作为评论发布的原因。) -
@barakmanos 完全正确。这就是为什么
T *p = malloc(sizeof *p);应该优先于T *p = malloc(sizeof(T));。
标签: c pointers memory-management