如何通过多个级别使用 void 指针将多个结构作为相同参数传递

How to pass multiple structs as same parameter using void pointer through multiple levels

我有多个结构,我正在尝试使用 void 指针为函数传递相同的参数,但它不起作用,我不知道为什么。

我创建了一个简单的测试用例来展示我对 运行 的兴趣。如果我在 repl 中使用 clang 编译它可以工作,但是如果我在 Linux mint 上使用 gcc 编译,我对第二个 printf 语句就没有意义了。

代码如下:

#include <stdio.h>

struct Test {
    char *name;
};

void *create();
void update(void *data);

struct Test *test_create();
void test_update(struct Test *test);

int main()
{
    void *currentData = create();

    update(currentData);

    return 0;
}

void *create()
{
    void *data = test_create();

    return data;
}

void update(void *data)
{
    struct Test *test = data;

    printf("a  %s\n", test->name);
    test_update(test);
}

struct Test *test_create()
{
    struct Test *test = &(struct Test) {
        .name = "test",
    };

    return test;
}

void test_update(struct Test *test)
{
    printf("b  %s\n", test->name);
}

我做错了什么?什么操作未定义?

test_create 中,您正在创建复合文字并返回指向它的指针。复合文字的生命周期是其封闭范围的生命周期,因此当函数 returns 返回指向不再存在的对象的指针时。这会触发 undefined behavior.

您应该改为动态分配内存,这样它将在函数 returns 之后存在。

struct Test *test_create()
{
    struct Test *test = malloc(sizeof *test);
    test->name = "test";

    return test;
}

确保在不再使用时 free 此内存。