【发布时间】:2020-12-05 10:09:57
【问题描述】:
我正在尝试使用变量的 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;
感谢任何帮助和/或建议...
【问题讨论】:
标签: c void void-pointers