gpt4 book ai didi

带指针的 C 深拷贝结构

转载 作者:太空宇宙 更新时间:2023-11-04 02:36:21 24 4
gpt4 key购买 nike

我是 C 的新手,需要解决以下问题。

我有一个读取小型 bmp (512x512) 图像的项目。我已经设法改变颜色并将其镜像(水平和垂直)。虽然我现在需要它转动 -90°。我无法正常工作的函数是 deepCopyBitmap()

我在 *copy->raster[i] 上不断收到以下错误:

indirection requires pointer operand ('PIXEL' (aka 'struct _pixel') invalid)

旋转 (512x512)

typedef struct _pixel {
unsigned char blue;
unsigned char green;
unsigned char red;
} PIXEL;

typedef struct _bitmap {
char file_path[PATH_MAX+1];
char magic_number[3];
unsigned int size;
unsigned char application[5];
unsigned int start_offset;
unsigned int bitmapHeaderSize;
unsigned int width;
unsigned int height;
unsigned short int depth;
unsigned char* header;
PIXEL* raster;
} BITMAP;

void rotate(BITMAP* bmp) {
int i;
int j;
PIXEL* originalPixel;
BITMAP* originalBmp;

deepCopyBitmap(bmp, originalBmp);

for(j=1; j <= bmp->height; j++) {
for(i=1; i <= bmp->width; i++) {
originalPixel=getPixel(originalBmp->raster, bmp->width, bmp->height, j, i);
setPixel(bmp->raster, bmp->width, bmp->height, (bmp->width + 1 - i), j, originalPixel);
}
}
}

void deepCopyBitmap(BITMAP* bmp, BITMAP* copy) {
*copy = *bmp;
if (copy->raster) {
copy->raster = malloc(sizeof(*copy->raster));
for (int i = 0; i < copy->height; i++) {
copy->raster[i] = malloc(sizeof(*copy->raster[i]));
memcpy(copy->raster[i], bmp->raster[i], sizeof(*copy->raster[i]));
}
}
}

更新

void deepCopyBitmap(BITMAP* bmp, BITMAP* copy) {
copy = malloc(sizeof(BITMAP));
*copy = *bmp;
if (copy->raster) {
size_t total_size = copy->height * copy->width * sizeof(PIXEL);
copy->raster = malloc(total_size);
memcpy(copy->raster, bmp->raster, total_size);
}
}

最佳答案

你在这里只分配一个PIXEL:

        copy->raster = malloc(sizeof(*copy->raster));

但是,您至少需要 copy->height PIXEL 才能使此迭代工作:

        for (int i = 0; i < copy->height; i++) {

在这里,你又只分配了一个PIXEL:

            copy->raster[i] = malloc(sizeof(*copy->raster[i]));

但是,您可能打算复制 copy->width PIXEL,而不是一个:

            memcpy(copy->raster[i], bmp->raster[i], sizeof(*copy->raster[i]));
}

您真正想要做的是分配copy->height * copy->width PIXEL,然后从原始文件中复制它们。

        size_t total_size = copy->height * copy->width * sizeof(PIXEL);
copy->raster = malloc(total_size);
memcpy(copy->raster, bmp->raster, total_size);

关于带指针的 C 深拷贝结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36711384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com