【问题标题】:change value of struct using void pointer使用 void 指针更改结构的值
【发布时间】: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。您只是在ptemp 中交换地址。
  • @FiddlingBits 这就是问题所在,我不知道它是什么样的结构,所以我无法知道大小。
  • 你能把字节数作为变量传递吗?
  • 你认为while (1);main() 底部的语句在做什么?

标签: c pointers casting void


【解决方案1】:

我希望 t_struc1 的值 t_struct2 ...

void * 通常用作函数参数,当该函数必须适应处理多种输入类型时。通常,因为函数知道数据是什么类型很重要,所以还必须有一个参数来告诉函数如何转换void * 数据。在这种情况下,我们知道接收类型是什么,因此转换将相当于:

struct test_struct *new = (struct test_struct *)p;  

如下图:

原谅我的typedefs,(可读性偏好。)但以下显示了如何将值从一个结构分配给另一个结构:

typedef struct test_struct {
        int test_int;
        char test_char;
}TEST;
TEST t_struct1;
TEST t_struct2;

void do_something_with_struct(void *p){

    TEST *new = (TEST *)(p);    //create a temporary pointer and with a cast
                                //assign it to point to the argument `p`
    new->test_char = t_struct2.test_char;//make assignments of values
    new->test_int =  t_struct2.test_int;
    p = new; //update p
}

int main(void) {
    t_struct2.test_char = 'b';
    t_struct2.test_int  = 2;

    do_something_with_struct((void*)&t_struct1);
    t_struct1;//because of global scope, changes made in function 
              //are visible here. (t_struct1 == t_struct2)
    printf("t_struct2.test_char: %c\nt_struct2.test_int: %d\n" \
        "t_struct1.test_char: %c\nt_struct1.test_int: %d\n" \
        "(Hit any key to exit.)", \
        t_struct2.test_char,t_struct2.test_int,  \        
        t_struct1.test_char,t_struct1.test_int);

    return 0;
}

【讨论】:

    猜你喜欢
    • 2016-03-21
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 2016-05-12
    • 2017-04-29
    • 1970-01-01
    相关资源
    最近更新 更多