简体   繁体   English

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

[英]malloc - runtime memory pointer type allocation

I don't know how to use malloc correctly when I need my code to determine it's type at runtime. 当我需要我的代码在运行时确定其类型时,我不知道如何正确使用malloc。 How do I declare one buffer in my header that can use either one of two different structs using malloc during runtime? 如何在运行时期间使用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;
    }
}

I am getting an error that reads: 我收到一条错误消息:
//error: Subscript of pointer to incomplete type 'void'

I was hoping that by using a void pointer it wouldn't care what type I end up using with malloc for my buffer. 我希望通过使用void指针,不必关心最终将malloc用于缓冲区的类型。

Is there a way to let buffer be filled with either rgb_16 or half_16 at runtime? 有没有办法让rgb_16half_16在运行时填充缓冲区?

First time posting here so please let me know if I should be formatting my post in a different way. 第一次在这里发布,所以请让我知道我是否应该以其他方式格式化我的帖子。 Thank you. 谢谢。

Right after if( tiff.sample_format == 3) { , you need something like half_16* h = (half_16*) buffer . if( tiff.sample_format == 3) { ,您需要使用half_16* h = (half_16*) buffer The compiler has no way to know what type buffer is, and so has no idea how far to go to get to the x 'th entry. 编译器无法知道什么是类型buffer ,因此也无法知道到达第x个条目的距离。 But with h[x] , it does since h is of type half_16* . 但是使用h[x]可以,因为h的类型为half_16*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM