malloc - 运行时内存指针类型分配

malloc - runtime memory pointer type allocation

本文关键字:类型 分配 指针 内存 运行时 malloc      更新时间:2023-10-16

当我需要我的代码在运行时确定它的类型时,我不知道如何正确使用 malloc。如何在标头中声明一个缓冲区,该缓冲区可以在运行时使用 malloc 使用两种不同结构之一?

struct rgb_16 {
    unsigned short r;
    unsigned short g;
    unsigned short b;
};
struct half_16 {
    half r;
    half g;
    half b;
};
(void*)buffer;
if(sample_format == 1) {
    buffer = (rgb_16*)malloc(width * height * sizeof(rgb_16));
}
if(sample_format == 3) {
    buffer = (half_16*)malloc(width * height * sizeof(half_16));
}
if(tiff.sample_format == 3) {
    // data is float. do not normalize
    for(int x = 0; x < rgba.size(); x++) {
        rgba[x].r = (half)tiff.buffer[x]
                        .r; // error: Subscript of pointer to incomplete type 'void'
        rgba[x].g = (half)tiff.buffer[x]
                        .g; // error: Subscript of pointer to incomplete type 'void'
        rgba[x].b = (half)tiff.buffer[x]
                        .b; // error: Subscript of pointer to incomplete type 'void'
        rgba[x].a = 1.0;
    }
}

我收到一条错误消息:
//error: Subscript of pointer to incomplete type 'void'

我希望通过使用 void 指针,它不会关心我最终使用 malloc 作为缓冲区的类型。

有没有办法让缓冲区在运行时用rgb_16half_16填充?

第一次在这里发帖,所以请让我知道我是否应该以不同的方式格式化我的帖子。谢谢。

if( tiff.sample_format == 3) {之后,你需要类似 half_16* h = (half_16*) buffer 的东西。编译器无法知道buffer是什么类型,因此不知道要走多远才能到达第 x 个条目。但是对于h[x],它确实如此,因为hhalf_16*型。