当我需要我的代码在运行时确定它的类型时,我不知道如何正确使用 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_16
或half_16
?
第一次在这里发帖,所以如果我应该以不同的方式格式化我的帖子,请告诉我。谢谢。
最佳答案
在 if( tiff.sample_format == 3) {
之后,您需要像 half_16* h = (half_16*) buffer
这样的东西。编译器无法知道 buffer
是什么类型,因此不知道要到达第 x
条目要走多远。但是对于 h[x]
,它确实如此,因为 h
是 half_16*
类型。
关于c++ - malloc - 运行时内存指针类型分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56310268/