将变量作为 Void* 传递然后再转换的 C 语法?

C Syntax for Passing Variables as Void* and Then Casting Later?

我正在尝试为变量使用 void* 指针编写一个通用的“更新我的结构”。看看:

typedef enum{
        aa, bb
}myEnum;

typedef struct myStruct{
        uint8_t         a;
        uint16_t        b;
}myStr;

// - - - - - - - - - - - - - - - - - - - - - - - - - - - -

void updateStr( myStr* thingee, myEnum flag, void* value ){
        switch( flag ){
                case aa:
                        thingee->a = (uint8_t*)value;
                        break;
                case bb:
                        thingee->b = (uint16_t*)value;
                        break;
        }
}

int main(){
        myStr* thingee = (myStr*)malloc( sizeof(myStr) );
        uint8_t  data1 = 123;
        uint16_t data2 = 456;

        updateStr( thingee, aa, data1 );
        updateStr( thingee, bb, data2 );

        free( thingee );
        return 1;
}

编译器讨厌这个:

# gcc -Wall toy.c
toy.c: In function ‘updateStr’:
toy.c:27:15: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
    thingee->a = (uint8_t*)value;
               ^
toy.c:30:15: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
    thingee->b = (uint16_t*)value;
               ^
toy.c: In function ‘main’:
toy.c:41:26: warning: passing argument 3 of ‘updateStr’ makes pointer from integer without a cast [-Wint-conversion]
  updateStr( thingee, aa, data1 );
                          ^~~~~
toy.c:24:6: note: expected ‘void *’ but argument is of type ‘uint8_t {aka unsigned char}’
 void updateStr( mystr* thingee, myEnum flag, void* value ){
      ^~~~~~~~~
toy.c:42:26: warning: passing argument 3 of ‘updateStr’ makes pointer from integer without a cast [-Wint-conversion]
  updateStr( thingee, bb, data2 );
                          ^~~~~
toy.c:24:6: note: expected ‘void *’ but argument is of type ‘uint16_t {aka short unsigned int}’
 void updateStr( myStr* thingee, myEnum flag, void* value ){
      ^~~~~~~~~
#

我的尝试可行吗?如果是这样,谁能帮我解决语法问题?我真的只需要知道如何调用我的 updateStr() 函数...

updateStr( thingee, aa, data1 );

...以及 updateStr() 应该如何将 void* 转换回我想要的数据类型...

thingee->a = (uint8_t*)value;

感谢任何帮助and/or建议...

您忘记取消引用您的指针。应该是

void updateStr( myStr* thingee, myEnum flag, void* value ){
        switch( flag ){
                case aa:
                        thingee->a = *(uint8_t*)value;
                        break;
                case bb:
                        thingee->b = *(uint16_t*)value;
                        break;
        }
}

此外,updateStr 希望您将指针传递给它,但您没有。你应该这样称呼它

updateStr( thingee, aa, &data1 );
updateStr( thingee, bb, &data2 );