[英]dynamic type variable with void pointer (eventuelly dynamic typecasting) in C
我只是问动态类型的变量(不是真正的动态,但应该在运行时确定),情况是这样的:
我有一个函数,它接受一个双精度数组,将其转换为整数并写入文件,该整数可以具有不同的Bitlength,例如8、16和32。由于它是一个数组,我想使用一个指针来访问最终值。结果(数组)。 因此,我现在将空指针与malloc和switch case一起使用,但是当我尝试访问或修改此数组时,需要在每个地方添加switch case,我的问题是,有没有更好的方法呢?
当前代码如下:
void foo(double * arr, int len, int iBits, FILE *fh)
{
void * newArr;
int iBytePerElement, iBase,i;
iBytePerElement = iBits / 8;
iBase = (1 << (iBits - 1)) - 1;
switch (iBytePerElement)
{
case 1:
{
newArr = (int8_t *) malloc(sizeof(int8_t)*len);
break;
}
case 2:
{
newArr = (int16_t *) malloc(sizeof(int16_t)*len);
break;
}
case 4:
{
newArr = (int32_t *) malloc(sizeof(int32_t)*len);
break;
}
}
for (i = 0; i < len; ++i)
{
switch (iBitPerElement)
{
case 1:
{
((int8_t *)newArr)[i] = (int8_t)(arr[i]*iBase);
break;
}
case 2:
{
((int16_t *)newArr)[i] = (int16_t)(arr[i]*iBase);
break;
}
case 4:
{
((int32_t *)newArr)[i] = (int32_t)(arr[i]*iBase);
break;
}
}
}
fwrite(newArr, iBytePerElement, iBytePerElement*len,fh);
}
对未定义的示例代码(注释)可能意味着什么做一些假设,这是我的处理方法:
#include <stdint.h>
#include <stdlib.h>
#include <limits.h>
void *foo(double * arr, int len, int iBits) //should return the malloced array not void
{
void * newArr;
int iBytePerElement, iBase, i;
iBytePerElement = iBits / 8;
iBase = (1 << (iBits - 1)) - 1;
if(NULL==(newArr = malloc(iBits/CHAR_BIT))) return NULL; //replace the first switch
//which obviously meant to alloc sizeof(int16_t)*len in the case 2 branch (not (sizeof(int8_t)*len) etc
for (i = 0; i < len; ++i) {
switch(iBytePerElement){
break; case 1: ((int8_t *)newArr)[i] = arr[i]*iBase;
break; case 2: ((int16_t *)newArr)[i] = arr[i]*iBase;
break; case 4: ((int32_t *)newArr)[i] = arr[i]*iBase;
}
}
return newArr;
}
基本上,您只需要第二个开关。
如果您想摆脱第二个开关,可以用一些函数指针播放代替它。 例如:
#include <stdint.h>
#include <stdlib.h>
#include <limits.h>
#define MK_FN(Bits) \
void to##Bits(void *newArr, double const*arr, int len) \
{ \
int i; for(i=0; i < len; i++) ((int##Bits##_t *)newArr)[i] = arr[i]*((1<<(Bits-1)-1)); \
}
MK_FN(8)
MK_FN(16)
MK_FN(32)
void *foo(double * arr, int len, int iBits) //should return the malloced array not void
{
void * newArr;
int iBytePerElement = iBits / 8;
if(NULL==(newArr = malloc(iBits/CHAR_BIT))) return NULL;
((void (*[])(void *,double const*, int)){ [1]=to8, [2]=to16, [4]=to32, })[iBits](newArr,arr,len);
return newArr;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.