c - 使用基本结构从 void* 中提取值

标签 c struct

我的项目中有许多类型的结构,另一个结构包含指向这些结构之一的指针。如,

struct one{int num = 1;};
struct two{int num = 2;};
struct three{int num = 3;};

// These structs hold many other values as well, but the first value is always `int num`.

我有另一个结构保存对这些结构的引用。我不得不使用 void*因为我不知道将引用这些结构中的哪一个。
struct Holder{void* any_struct};

我的问题是,我需要这些结构中的值,但我有一个 void指针,我可以声明一个基结构,第一个变量是 int ,转换它,并用它来提取 num来自这些结构的变量,例如:
struct Base{int num};
((Base*) Holder->any_struct)->num
// Gives 1, 2 or 3

最佳答案

如果您只需要提取 num ,您可以使用 memcpy .
假设它总是 int并且永远在前,永远在场。

int num = 0;
memcpy(&num, Holder->any_struct, sizeof(int));
// Gives 1, 2 or 3 in num.

C99 标准第 6.7.2.1 条第 13 条:

A pointer to a structure object, suitably converted, points to its initial member. There may be unnamed padding within a structure object, but not at its beginning.



有关标准的更多信息 this answer .

关于c - 使用基本结构从 void* 中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58641549/

相关文章:

c - 使用 "while"检查是否有空行C

c - 如何使用C发出警报声?

c - Malloc 不断返回相同的指针

c - 在不同编译器上具有显式宽度成员的结构对齐

C malloc 二维结构数组(带行和列)

c - 更新嵌套 C 结构数组的正确方法是什么?

go - 同一结构中的多个互斥体?

c - c中的结构数组在读取c中的文本文件后未获取其所有值

c - 在没有段错误的结构中使用指针

c - mvnpdf 与常规正态(高斯)PDF - matlab/C