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

标签 c++

当我需要我的代码在运行时确定它的类型时,我不知道如何正确使用 malloc。如何在我的 header 中声明一个缓冲区,该缓冲区可以在运行时使用 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;
    }
}

我收到一条错误消息:
//错误:指向不完整类型'void'的指针的下标

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

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

第一次在这里发帖,所以如果我应该以不同的方式格式化我的帖子,请告诉我。谢谢。

最佳答案

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

关于c++ - malloc - 运行时内存指针类型分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56310268/

相关文章:

c++ - 共享库的 TX 文件扩展名?

c++ - 异步 IO 的整洁代码

c++ - 如何防止Windows控制台上的Enter键自动滚动

c++ - 在超过 1 个(多个) 'std::map' s 或 'std::set' s 中查找 key 的最佳方法?

c++ - 改进的 K-means 聚类(Ward 准则)速度改进

C++:32 与 64 位流操作

c++ - 基本的 C++ 内存分配和 strlen

c++ - 我可以写一个封闭的 socket 并强行纠正断管的错误吗?

c++ - 在 OpenGL 上下文中使用 SDL 传输

c++ - 共享数据文件映射