【发布时间】:2021-04-09 10:43:11
【问题描述】:
嘿,我正在尝试复制从另一个图像中创建的 SDL_Color 数组。但是对于某些图像,我得到:
进程以退出代码 -1073741819 (0xC0000005) 结束
它适用于 20 x 20 像素的图像,但它适用于 50 x 50 的图像... 这是我的代码:
FILE *debugFile = fopen("C:\\Users\\Clement\\Documents\\coding\\ImageOfCLife\\debug.txt", "w+");
int imgWidth, imgHeight, channels;
unsigned char *img = stbi_load("C:\\Users\\Clement\\Documents\\coding\\ImageOfCLife\\star.jpg", &imgWidth,
&imgHeight, &channels, 0);
fprintf(debugFile, "Loaded image with a width of %dpx, a imgHeight of %dpx and %d channels\n", imgWidth, imgHeight, channels);
dRulesLen = sizeof(deathRules);
bRulesLen = sizeof(birthRules);
if (img == NULL) {
fprintf(debugFile, "Error in loading the image\n");
exit(3);
}
int ch, pix;
SDL_Color **stateMatrix1 = (SDL_Color **) malloc(imgHeight * sizeof(SDL_Color*));
if (stateMatrix1 == NULL) {
fprintf(debugFile,"Unable to allocate memory\n");
exit(1);
}
for (int i = 0; i < imgHeight; ++i) {
stateMatrix1[i] = (SDL_Color *) malloc(imgWidth * sizeof(SDL_Color));
}
for (ch = 0; ch < imgHeight; ch++) {
printf("{");
for (pix = 0; pix < imgWidth; pix++) {
unsigned bytePerSDL_Color = channels;
unsigned char *SDL_ColorOffset = img + (pix + imgHeight * ch) * bytePerSDL_Color;
SDL_Color p = initSDL_Color(SDL_ColorOffset);
stateMatrix1[ch][pix] = p;
printSDL_Color(p);
printf(", ");
}
printf("}\n");
}
SDL_Color stateMatrix2[imgHeight][imgWidth];
memcpy(stateMatrix2, stateMatrix1, imgWidth*imgHeight*sizeof(SDL_Color));
最后一行是根据the debugger的问题 我试过了
memcpy(stateMatrix2, stateMatrix1, sizeof(stateMatrix2))
也是,但我得到了相同的结果。
我使用 minGW 和 Clion 在 Windows 10 上工作。我希望你能帮助我解决这个问题。
我还尝试将SDL_Color stateMatrix2[imgHeight][imgWidth]; 替换为:
SDL_Color **stateMatrix2 = (SDL_Color **) malloc(imgHeight * sizeof(SDL_Color*));
if (stateMatrix2 == NULL) {
fprintf(debugFile,"Unable to allocate memory\n");
exit(1);
}
for (int i = 0; i < imgHeight; ++i) {
stateMatrix2[i] = (SDL_Color *) malloc(imgWidth * sizeof(SDL_Color));
}
但我遇到了同样的问题。
我忘了说,但我希望 ant 能够同时使用 stateMatrix 作为函数的参数。
为了解决这个问题,我使用了下面解释的 Olaf 解决方案: 我保留了:
SDL_Color **stateMatrix1 = (SDL_Color **) malloc(imgHeight * sizeof(SDL_Color*));
if (stateMatrix1 == NULL) {
fprintf(debugFile,"Unable to allocate memory\n");
exit(1);
}
for (int i = 0; i < imgHeight; ++i) {
stateMatrix1[i] = (SDL_Color *) malloc(imgWidth * sizeof(SDL_Color));
}
为矩阵和使用分配内存:
for (int i = 0; i < imgHeight; ++i) {
memcpy(stateMatrix2[i], stateMatrix1[i], imgWidth * sizeof(SDL_Color));
}
执行复制。 我还验证了两个矩阵没有链接,没有问题。
【问题讨论】:
-
stateMatrix1不是连续的内存块。它由许多单独的malloc内存块组成,因此不能用单个memcpy复制。 -
stateMatrix2是一个二维数组,而stateMatrix1是一个指针数组,指向SDL_Color->不同类型的数组。 -
@kaylum 哦,所以解决方案是循环使用
memcpy(stateMatrix2[i], stateMatrix1[i], imgWidth*sizeof(SDL_Color)? -
@OlafDietsche 所以我必须以与矩阵 1 相同的方式声明 matrix2 吗?
-
在C中,
malloc的返回不需要强制转换,没有必要。见:Do I cast the result of malloc?
标签: c multidimensional-array segmentation-fault memcpy