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

标签 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)
}

最佳答案

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

关于在 C 中将 void* 从短数组 (short*) 转换为 float 数组 (float),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22539332/

相关文章:

c++ - 指针减法和替代方案

c - 将指向数组的指针传递给另一个函数 C

c - 释放堆栈的二维数组

c - 创建4个子进程

c - 结构类型的排序数组

c - 使用链接在一起的多个箭头运算符 (->) 有什么缺点吗?

c - 我对 SPOJ 的解决方案中的段错误 - 下一个回文

c - 如何转换我从文件 (char) 中获取的值并将这些值存储到 double 组中?

arrays - 使用 strncpy() 时缓冲区溢出内存困惑?

c - 是否允许返回具有灵活数组成员的结构?