int foo(int grade,void * factor) - 如何在函数内使用该因子?

时间:2014-11-21 17:27:36

标签: c c99

我的情况是factor变量可以指针intfloat,该函数的签名必须看起来如下所示:

int calcFactor(int grade, void *factor) {
    return (grade * (*factor));
}

解除引用factor有什么问题?我假设因子是void *类型的指针,因此我在使用它之前使用(*factor)取消引用它。

我在这里缺少什么?为什么海湾合作委员会对我大吼大叫?

ex_3.c: In function `calcFactor':
ex_3.c:51:19: warning: dereferencing `void *' pointer [enabled by default]
  return (grade * (*factor));
                   ^
ex_3.c:51:2: error: void value not ignored as it ought to be
  return (grade * (*factor));
  ^

2 个答案:

答案 0 :(得分:3)

#include <stdio.h>

#define Float(x) (x << 1)
#define Int(x) (x << 1) + 1
//or  use the least significant bit from that pointer of int and float is an even address    
int calcFactor(int grade, void *factor);

int main(){
    int factor_i = 10;
    float factor_f = 0.5;
    printf("%d\n", calcFactor(Float(85), (void*)&factor_f));
    printf("%d\n", calcFactor(Int(85), (void*)&factor_i));
    return 0;
}

int calcFactor(int grade, void *factor) {
    return (grade >> 1) * (grade & 1 ?  *(int*)factor : *(float*)factor);
}

#include <stdio.h>
#include <stdint.h>

#define INT 1

int calcFactor(int grade, void *factor);

int main(){
    int factor_i = 10;
    float factor_f = 0.5;
    printf("%d\n", calcFactor(85, (void*)&factor_f));
    printf("%d\n", calcFactor(85, (void*)((uintptr_t)&factor_i | INT)));
    return 0;
}

int calcFactor(int grade, void *factor) {
    return grade * ((uintptr_t)factor & INT ?  *(int*)((uintptr_t)factor ^ INT) : *(float*)factor);
}

答案 1 :(得分:1)

您需要将值因子点转换为值可以是多个值之前的值 尝试

return (grade * (*(int *)factor);