将void *从short(short *)数组转换为C中的float(float)数组

时间:2014-03-20 16:30:37

标签: c arrays pointers

我有一个包含void*的结构void*是一个短裤数组(short*),例如-6,-113, -110,...,n

我想将所有这些美妙的短片转换成浮点数。例如-6 - > -6.0000000

typedef struct datablock
{
  int maxRows;
  void *data;
} DataBlock;

// imagine *data points to a short* --> { -6, -113, -100, -126 }

static void Read(params here)
{
  float *floatData;
  data = (float *) DataBlock->data; // obvious fail here
  // data will now look like --> { -1.Q#DEN00, -1.Q#ENV00, ..., n} 
  // i assume the compiler is not handling the conversion for me
  // which is why the issue comes up
  // **NOTE** Visual Studio 2013 Ultimate is the enviorment (windows 8)
}

1 个答案:

答案 0 :(得分:1)

typedef struct datablock
{
  int maxRows;
  void *data;
} DataBlock;

[...]

  DataBlock db = ... <some init with shorts>;

  DataBlock db_f = {db.maxRows, NULL};
  db_f.data = malloc(db_f.maxRows * sizeof(float));
  /* Add error checking here. */
  for (size_t i = 0; i < db_f.maxRows; ++i)
  {
    *(((float *) db_f.data) + i)  = *(((short *) db.data) + i);
  }

  /* Use db_f here. */

  free(db_d.data); /* Always tidy up before leaving ... */

正如 Sylvain Defresne 所提出的,使用临时指针更容易读取循环体:

  for (
    size_t i = 0, 
    short * src = db.data,
    float * dst = db_f.data;
    i < db_f.maxRows; 
    ++i)
  {
    dst[i] = src[i];
  }
相关问题