首页 > 解决方案 > 在 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);

从合法的意义上说,这种方式可以吗?有没有另一种方法可以用更少的代码和更通用的方法来做到这一点?

标签: cmemorymemory-management

解决方案


您将需要知道许多地方的像素大小。所以定义一个函数来计算像素大小并在每次需要时使用它。

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);
}

推荐阅读