【发布时间】:2010-12-25 13:59:38
【问题描述】:
我正在处理一个二维结构数组,它是另一个结构的一部分。这不是我经常做的事情,所以我遇到了问题。这个函数在接近末尾的“测试”for循环后最终失败。它会在出现故障之前正确打印出一行。
将数据读入虚拟二维结构数组的代码部分工作得很好,所以它必须是我的分配数组才能成为另一个结构(imageStruct)的一部分。
任何帮助将不胜感激!
/*the structure of each pixel*/
typedef struct
{
int R,G,B;
}pixelStruct;
/*data for each image*/
typedef struct
{
int height;
int width;
pixelStruct *arr; /*pointer to 2-d array of pixels*/
} imageStruct;
imageStruct ReadImage(char * filename)
{
FILE *image=fopen(filename,"r");
imageStruct thisImage;
/*get header data from image*/
/*make a 2-d array of of pixels*/
pixelStruct imageArr[thisImage.height][thisImage.width];
/*Read in the image. */
/*I know this works because I after storing the image data in the
imageArr array, I printed each element from the array to the
screen.*/
/*so now I want to take the array called imageArr and put it in the
imageStruct called thisImage*/
thisImage.arr = malloc(sizeof(imageArr));
//allocate enough space in struct for the image array.
*thisImage.arr = *imageArr; /*put imageArr into the thisImage imagestruct*/
//test to see if assignment worked: (this is where it fails)
for (i = 0; i < thisImage.height; i++)
{
for (j = 0; j < thisImage.width; j++)
{
printf("\n%d: R: %d G: %d B: %d\n", i ,thisImage.arr[i][j].R,
thisImage.arr[i][j].G, thisImage.arr[i][j].B);
}
}
return thisImage;
}
(如果您想知道我为什么首先使用虚拟数组,那是因为当我开始编写这段代码时,我不知道如何去做我现在想做的事情。)
编辑:有人建议我没有在 imageStruct 的 typedef 中正确初始化二维数组。如果确实是问题,谁能帮我纠正这个问题?
【问题讨论】:
-
顺便说一句:如果您正在使用像素,您可能需要考虑使用平面线性缓冲区,然后使用缓冲区 [y*width + x] 索引点 (x,y)。这很常见,如果您必须将该缓冲区传递给可能采用这种格式的其他人的代码,这可能会有所帮助。
-
感谢您的建议!我会考虑的。然后我就可以忘记二维数组的混乱了!
-
我得出的结论是,尝试将二维数组作为结构的一部分是没有希望的。我已经切换到一维数组,现在一切正常。感谢所有帮助过我的人,这是迄今为止我遇到的最有帮助的编程论坛!