c - 在 C 中为不同数据类型分配内存的正确方法是什么?
问题描述
我正在将图像读入动态分配的数组中,图像像素类型可以是以下任何一种类型:
typedef enum {
Byte = 1,//unsigned char
Int32 = 2,//int
Float32 = 3,//float
Float64 = 4//double
}DataType;
我正在考虑使用块在指针switch
上分配内存:void
int NumPix = GetImageSize(Image);
DataType theDataType = GetImageDataType(Image);
void *data;
switch (theDataType)
{
case Byte:
data = (unsigned char *)malloc(NumPix * sizeof(unsigned char));
break;
case Int32:
data = (int *)malloc(NumPix * sizeof(int));
break;
case Float32:
data = (float *)malloc(NumPix * sizeof(float));
break;
case Float64 :
data = (double*)malloc(NumPix * sizeof(double));
break;
}
// do something with data
free(data);
从合法的意义上说,这种方式可以吗?有没有另一种方法可以用更少的代码和更通用的方法来做到这一点?
解决方案
您将需要知道许多地方的像素大小。所以定义一个函数来计算像素大小并在每次需要时使用它。
size_t pixel_size(DataType type) {
switch (type) {
case Byte: return sizeof(unsigned char);
case Int32: return sizeof(unsigned int); // Shouldn't this be uint32_t?
case Float32: return sizeof(float);
case Float64: return sizeof(double);
}
}
// Allocate an image with indeterminate content.
// Return NULL if the allocation fails.
void *allocate_indeterminate_image(DataType type, size_t x, size_t y) {
size_t pixel_count = x * y; // overflow checking omitted
size_t byte_count = pixel_count * pixel_size(type); // overflow checking omitted;
return malloc(byte_count);
}
// Allocate an image with all-bits-zero. On almost every platform,
// this means that each pixel has the value 0 (+0.0 for floats).
// Return NULL if the allocation fails.
void *allocate_blank_image(DataType type, size_t x, size_t y) {
size_t pixel_count = x * y; // overflow checking omitted
size_t bytes_per_pixel = pixel_size(type);
return calloc(pixel_count, bytes_per_pixel);
}
推荐阅读
- android - 有什么方法可以将 Jetpack Compose 字体转换为原生字体?
- python - 使用请求从网页获取端口时遇到问题
- php - DOMElement 绝对存在,但是 PHP 给出了致命错误,说它不存在,就在说它存在之后
- dll - REGSVR32 查找 dll 在注册表中的位置
- swiftui - 使用文本和滑块 swiftUI 创建 HStack 的垂直堆栈
- python - 仅对满足 Python 中特定条件的像素执行 2D 卷积
- c# - 如果输入参数不为空,MySql 更新
- javascript - 如何以角度向API服务异步添加数据(需要迭代两次)?
- android - Android 向上滑动以打开画廊,就像在 whatsapp 相机中一样
- python - Seaborn 中的自定义图表格式