gpt4 book ai didi

c - union 成员如何拥有指向 union 实例的指针?

转载 作者:太空狗 更新时间:2023-10-29 16:00:16 31 4
gpt4 key购买 nike

我可能把这个复杂化了..

我正在尝试在 Arduino 上用 C 语言为嵌入式应用程序制作一个相当可重用的分层菜单系统。我有结构来表示不同类型的菜单项,包括那些子菜单,以及这些菜单项的 union 是一个通用的菜单项。菜单条目数组是菜单的一个级别。子菜单项具有指向另一个菜单项数组的指针。

问题是,子菜单条目是 union 的成员,因此需要在 union 之前定义它。但它有一个指向该 union 实例数组的指针,这会导致编译错误,因为该 union 尚未定义。

是否有处理此问题的类型安全方法,或者我在子菜单条目中的指针是否必须为 void*?

代码:

typedef enum {UI_STATE_HOME, UI_STATE_MENU, UI_STATE_DIALOG} te_UIState;
typedef enum {UI_ENTRY_SUBMENU, UI_ENTRY_NUMERIC_INT, UI_ENTRY_NUMERIC_FLOAT, UI_ENTRY_BOOL, UI_ENTRY_DISCRETE} te_UIEntryType;

/* Typedefs for the different types of entry
*
*/

typedef struct {
char* entryName; // pointer to one of our string entries, eg MNU_Light
te_UIEntryType entryType;
} tsEntry;

typedef struct {
char* entryName;
te_UIEntryType entryType;
int (* finalIntHandler)(int selectedValue); //The function that should be called when a number has been selected
int (* initialIntValue) (); //The function that should be called to obtain the starting value for the selector
} ts_EntryInt;

typedef struct {
char* entryName;
te_UIEntryType entryType;
int (* finalIntHandler)(float selectedValue);
float (* initialSingleValue) ();
} ts_EntrySingle;

typedef struct {
char* entryName;
te_UIEntryType entryType;
int (* finalIntHandler)(bool selectedValue);
bool (* initialBoolValue) ();
} ts_EntryBool;

typedef struct {
char* entryName;
te_UIEntryType entryType;
int (* handler)();
char* (* optionalEntryNamePtrFunction)(); //If this points to a function, it'll be called to determine what text to display as the entry name.
// This is for things like enable/disable where the text changes depending on the present state.
} ts_EntryDiscrete;

typedef struct {
char* entryName;
const te_UIEntryType entryType = UI_ENTRY_SUBMENU;
void *entries[];
} ts_EntrySubmenu;


typedef union
{
tsEntry entry;
ts_EntryInt entryInt;
ts_EntrySingle entrySingle;
ts_EntryBool entryBool;
ts_EntryDiscrete entryDiscrete;
ts_EntrySubmenu entrySubmenu;
} tuEntry;

最佳答案

您需要转发声明tuEntry 以便您可以在ts_EntrySubmenu 中使用它。您需要为该 union 提供一个标记名称,以便稍后引用。

此外,在 C 中定义时,您不能将结构或 union 的字段初始化为默认值。您需要在每个相关实例中设置该字段。

typedef union tuEntry tuEntry;

typedef struct {
char* entryName;
const te_UIEntryType entryType; // no default value
tuEntry *entries[];
} ts_EntrySubmenu;


union tuEntry
{
tsEntry entry;
ts_EntryInt entryInt;
ts_EntrySingle entrySingle;
ts_EntryBool entryBool;
ts_EntryDiscrete entryDiscrete;
ts_EntrySubmenu entrySubmenu;
};

关于c - union 成员如何拥有指向 union 实例的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54908601/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com