malloc - 运行时内存指针类型分配
malloc - runtime memory pointer type allocation
当我需要我的代码在运行时确定它的类型时,我不知道如何正确使用 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_16
或half_16
填充?
第一次在这里发帖,所以请让我知道我是否应该以不同的方式格式化我的帖子。谢谢。
在if( tiff.sample_format == 3) {
之后,你需要类似 half_16* h = (half_16*) buffer
的东西。编译器无法知道buffer
是什么类型,因此不知道要走多远才能到达第 x
个条目。但是对于h[x]
,它确实如此,因为h
是half_16*
型。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 不能将 "void *" 类型的值分配给类型 "TCHAR" 的实体
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 将超出范围的整数分配给有符号字符类型
- C++将一个指针分配给另一个指针时执行的类型检查
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 c++ 中将一种结构类型分配给另一种类型
- 将返回的类型分配给一个脱口机类型
- 如何为多态性中的指定类型分配内存
- malloc - 运行时内存指针类型分配
- 不能将Const数据类型分配到非Const数据类中
- C++ 随机将枚举类型分配给变量
- 游戏实体类型分配
- 在单个语句中将类类型分配给该类的取消引用指针时执行哪些操作
- C++如何将数据类型分配给二进制序列
- 为类型分配唯一的整型标识符,编译时