我有一个包含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)
}

最佳答案

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

07-27 16:47