问题描述
我正在尝试使用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,data1 );
^~~~~
toy.c:24:6: note: expected ‘void *’ but argument is of type ‘uint8_t {aka unsigned char}’
void updateStr( mystr* thingee,void* value ){
^~~~~~~~~
toy.c:42:26: warning: passing argument 3 of ‘updateStr’ makes pointer from integer without a cast [-Wint-conversion]
updateStr( thingee,data2 );
^~~~~
toy.c:24:6: note: expected ‘void *’ but argument is of type ‘uint16_t {aka short unsigned int}’
void updateStr( myStr* thingee,void* value ){
^~~~~~~~~
#
我正在尝试的可能吗?如果是这样,有人可以在语法方面帮助我吗?我真的只需要知道如何调用我的updatestr()
函数...
updateStr( thingee,data1 );
...以及updatestr()
应该如何将void *转换回我想要的数据类型...
thingee->a = (uint8_t*)value;
感谢任何帮助和/或建议...
解决方法
您忘记了取消引用指针。应该是
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 );