【发布时间】:2016-02-08 12:36:06
【问题描述】:
所以我正在尝试编写一个程序来读取 ppm 文件并将其存储在内存中,我已经完成了所有颜色的工作,这个函数给我带来了问题:
typedef struct{
int red, green, blue;
} COLOR;
COLOR * getNextColor(FILE *fd);
COLOR **getColors(FILE *fd, int width, int height){
printf("\nentered get colors");
COLOR **colors = malloc(sizeof(COLOR*)*height);
printf("\nallocated %d space height",height);
int i,j;
for(i = 0; i < height; i++, colors++){
*colors = malloc(sizeof(COLOR)*width);
printf("\nallocated %d space width",width);
for(j = 0; j < width; j++, *colors++){
printf("\nlooping through to get the colors for point (%d,%d)", j,i);
//*colors = getNextColor(fd);
}
*colors -= width;
printf("\nmoved the pointer for *colors back %d spaces",width);
}
colors -= height;
printf("\nmoved the pointer for colors back %d spaces",height);
return colors;
}
我传入的文件指针当前指向第一种颜色的第一个数字,宽度 = 400,高度为 530。输出如下所示:
allocated 530 space height
allocated 400 space width
looping through to get the colors for point (0,0)
looping through to get the colors for point (1,0)
looping through to get the colors for point (2,0)
...
looping through to get the colors for point (398,0)
looping through to get the colors for point (399,0)
moved the pointer for *colors back 400 spaces
allocated 400 space width
looping through to get the colors for point (0,1)
looping through to get the colors for point (1,1)
...
looping through to get the colors for point (398,1)
looping through to get the colors for point (399,1)
moved the pointer for *colors back 400 spaces
allocated 400 space width
并且模式一直重复到
looping through to get the colors for point (399,36)
然后崩溃。有什么想法吗?
【问题讨论】:
-
很久以来我没有在 c++ 中做任何事情,我唯一看到并且不认为它相关的东西.. 是你做 *colors -= width;并且不使用 * later colors -= height;
-
你试过什么?您是否尝试过使用调试器来查看崩溃的确切位置?通常这是一个有用的提示。
-
@LuisTellez 这是一个见仁见智的问题,但在某些情况下 VS 会浪费很多时间(例如,当您不使用 Windows 时)。
-
只要不要用指针到指针编写晦涩难懂的代码,就不会写出如此难以发现的错误。改为使用指向真实二维数组的指针。
-
@James 最重要的是,它使您可以在相邻内存中分配一个二维数组,而不是分散在堆中的各个段。因此它可以用作任何其他二维数组,例如您可以在其上使用标准函数 memcpy、memset、bsearch、qsort 等。而且只有一个 free() 调用,而不是一些重复调用 free() 的晦涩 for 循环。