【发布时间】:2020-09-13 10:32:12
【问题描述】:
我将我的问题简化为:
假设我有一个结构 (t_struct1),如果我将该结构传递给函数 (do_something_with_struct(...)),另一个结构 (t_struct2) 的值将被复制到第一个结构 (t_struct1) 中。所以基本上...
void do_something_with_struct(struct){
struct = struct2;
}
do_something_with_struct(struct1);
...需要发生。
我的程序中不允许的一些事情: 1.函数对结构体一无所知,所以我基本上不能将void指针强制转换为函数内部的结构体和2.函数的参数需要是一个void指针。
这是我正在使用的“真实”程序,但由于某种原因它不起作用。
struct test_struct {
int test_int;
char test_char;
};
struct test_struct t_struct1;
struct test_struct t_struct2;
void do_something_with_struct(void *p){
void* temp = (void*)&t_struct2;
p = temp;
}
int main(void) {
t_struct2.test_char = 'b';
t_struct2.test_int = 2;
do_something_with_struct((void*)&t_struct1);
// I want the values of t_struc1 to be the same as t_struct2 (so 2 and 'b'),
// but they aren't. Instead t_struct1 is is filled with random/default values.
while (1);
}
正如我上面提到的,该程序不工作。有没有人有一个解决方案/想法可以使我的程序正常工作。
提前致谢,
阿琼
【问题讨论】:
-
如果你知道
sizeof(struct test_struct),你可以使用memcpy。 -
顺便说一句,你从来没有真正写信给
t_struct1。您只是在p和temp中交换地址。 -
@FiddlingBits 这就是问题所在,我不知道它是什么样的结构,所以我无法知道大小。
-
你能把字节数作为变量传递吗?
-
你认为
while (1);在main()底部的语句在做什么?