如何将结构分配给通过参数传递的 void 指针?
How can I assign a struc to a void pointer passed through the paramters?
在我的代码中有一个结构
struct Test {
int a;
int b;
char c;
};
用我的函数:
int TestFunction(void* ptr){
struct Test test;
test.a = 0;
test.b = 1;
strcpy(c,"hello");
return 0;
}
现在 link 我传入的 void ptr 的临时结构
struct Test* temp = (struct Test*)ptr;
struct Test test = *temp;
这是 link strucs with void ptrs 的正确方法吗?有没有更简单的方法?
由于您希望能够修改指向的结构,因此您的示例代码不合适。它所做的是创建指向结构的本地副本并修改本地副本而不是原始对象。
你想做的是:
int TestFunction(void *ptr) {
struct Test *test = ptr;
test->a = 0;
test->b = 1;
return 0;
}
a->b
语法等同于 (*a).b
,这意味着它指的是 test
指向的任何内容。
在我的代码中有一个结构
struct Test {
int a;
int b;
char c;
};
用我的函数:
int TestFunction(void* ptr){
struct Test test;
test.a = 0;
test.b = 1;
strcpy(c,"hello");
return 0;
}
现在 link 我传入的 void ptr 的临时结构
struct Test* temp = (struct Test*)ptr;
struct Test test = *temp;
这是 link strucs with void ptrs 的正确方法吗?有没有更简单的方法?
由于您希望能够修改指向的结构,因此您的示例代码不合适。它所做的是创建指向结构的本地副本并修改本地副本而不是原始对象。
你想做的是:
int TestFunction(void *ptr) {
struct Test *test = ptr;
test->a = 0;
test->b = 1;
return 0;
}
a->b
语法等同于 (*a).b
,这意味着它指的是 test
指向的任何内容。