简体   繁体   English

将double传递给需要uint8_t *的函数

[英]Pass double to a function expecting uint8_t*

Suppose we have a function which takes double pointer as an argument and we want to modify that value: 假设我们有一个将双指针作为参数的函数,并且我们想修改该值:

void fun(uint8_t *arg1) {
    *arg1 = 2;
}

int main(void) {
    double a;
    fun((uint8_t*)&a); // does not work

    return 0;
}

Is this even possible? 这有可能吗?

What you are specifying is undefined behaviour : you can't cast the pointer to a different type. 您所指定的是未定义的行为 :您不能将指针转换为其他类型。

Your best bet is to create a uint8_t in main , pass a pointer to that to your function fun , then assign that modified value to the double. 最好的选择是在main创建一个uint8_t ,将指向它的指针传递给函数fun ,然后将该修改后的值分配给double。

Simplest solution is to use temporary variable: 最简单的解决方案是使用临时变量:

double a;
uint8_t b = a;
fun(&b);

Another solution is to use void* and tell used type with another parameter: 另一个解决方案是使用void*并使用另一个参数来告诉使用的类型:

void fun(void *arg1, int type) {
    switch(type)
        case TYPE_DOUBLE:
            *(double*)arg1 = 2;
            break;
        case TYPE_UINT8:
            *(uint8_t*)arg1 = 2;
            break;
     }
 }
void fun(uint8_t *arg1) {
    double a = 2;
    memcpy(arg1, &a, sizeof a);
}

像这样*(double *)arg1 = 2;fun内部键入变量arg1 *(double *)arg1 = 2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM