带指针的C深拷贝结构

时间:2016-04-19 07:26:51

标签: c struct deep-copy

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

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

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

  

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

ROTATION(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);
    }
}

1 个答案:

答案 0 :(得分:2)

您只需在此处分配一个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);