目标是使用动态数组构建“无限”树。
items[3]
- MENUITEM
- items[2]
- MENUITEM
-items[0]
- MENUITEM
- items[0]
- MENUITEM
- items[0]
- MENUITEM
- items[2]
- MENUITEM
- items[0]
- MENUITEM
- items[0]
我定义结构:
typedef struct MENUITEM {
char id, count;
char *description;
};
我可以通过以下方式动态分配项目:
char count;
MENUITEM items[], *items_ptr;
count++;
realloc( items_ptr, count * sizeof(struct MENUITEM) );
问题是在结构内部我无法再次分配结构本身,例如:
typedef struct MENUITEM {
char id, count;
char *description;
MENUITEM items[], *items_ptr;
};
编译器输出:错误:字段‘items’的类型不完整;我在这里做错了什么? 感谢您提供的任何帮助。
最佳答案
您需要使用struct MENUITEM *items_ptr;
。请注意 struct
一词的使用。
为什么你有 MENUITEM items[]
?它没有用于任何用途。
改为这样做:
typedef struct MENUITEM {
char id, count;
char *description;
struct MENUITEM *items;
} MENUITEM;
void foo() {
MENUITEM *root = (MENUITEM*)malloc(sizeof(MENUITEM));
root->id = 87;
root->count = 5;
root->items = (MENUITEM*)malloc(sizeof(MENUITEM)*root->count);
}
关于c - 在结构内部,如何定义与结构本身类型相同的结构数组(动态),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3498589/