[英]Creating an array of struct inside another struct and accessing the members of the struct inside the array in C
我想在另一个结构(也用 typedef 定义)内创建结构(用 typedef 定义)数组并访问数组内的结构成员,但我有点卡住了。 如果你能引导我走向正确的方向,我真的很感激。
我的代码是一个更大代码的一部分,所以我将尝试用一个示例代码来解释我的情况。 如果它不理解,我可以随时分享我的实际代码。
我在 header 文件中有两个结构;
#define MAX_COMP_COUNT 64
typedef struct Module Module;
typedef struct Component Component;
struct Module
{
Component** _CompArr[MAX_COMP_COUNT];
uint8_t _CompCount;
};
struct Component
{
uint8_t _page, _id;
};
我想在 Module 结构中的数组内添加 Component 结构(目前不需要动态大小。)
所以我在一个.c文件中写了这个function;
uint8_t AddComp(Module* mod, Component* _comp, uint8_t __page, uint8_t __id)
{
//Pass the corresponding data from component to component struct
_comp->_id = __id;
_comp->_page = __page;
//Add the component struct to the list on the Module Struct
mod->_CompArr[mod->_CompCount] = &_comp;
mod->_CompCount++;
//Return OK
return 0;
}
但是我试图通过数组访问结构的 id 成员,但我有点失败。 我不知道我是否滥用了某些东西或上面的部分定义错误。 如果您能纠正我,那将非常有帮助。 提前致谢。
uint8_t Module_Update(Module *mod)
{
for(uint8_t i = 0; i < mod->_CompCount; i++)
{
//This part is not working
if(*(mod->_CompArr[i])->_id == 0xFF)
//Do stuff
}
return 0;
}
编辑:我收到此错误;
错误:'*mod->_CompArr[(int)i]' 是一个指针; 你的意思是使用'->'吗?
简化,我们得到这个:
#include <stdint.h>
#define MAX_COMP_COUNT 64
typedef struct
{
uint8_t page;
uint8_t id;
} Component;
typedef struct
{
Component CompArr [MAX_COMP_COUNT];
uint8_t CompCount;
} Module;
然后相应地修改您的功能。 这是一个非常奇怪的 API 将 Component 作为指针传递,然后根据其他参数填充该 Component 结构的值 - 不要创建奇怪的 function 接口:而是假设 Component 已经由调用者填充:
void AddComp (Module* mod, Component* comp)
{
//Add the component struct to the list on the Module Struct
mod->CompArr[mod->CompCount] = comp;
mod->CompCount++;
}
或者,如果动态分配是一个选项:
void AddComp (Module* mod, uint8_t page, uint8_t id)
{
Component* comp = malloc(sizeof *comp);
comp->page = page;
comp->id = id;
mod->CompArr[mod->CompCount] = comp;
mod->CompCount++;
}
现在,您有很多似乎不必要的间接负载:
struct Module
{
Component **_CompArr[MAX_COMP_COUNT];
uint8_t _CompCount;
};
Component **_CompArr
中的二级指针没有理由。 您可以删除一级或二级间接:
使用单指针:
struct Module { Component* _CompArr[MAX_COMP_COUNT]; uint8_t _CompCount; };
您将在循环中使用结构作为
if(mod->_CompArr[i]->_id == 0xFF)...
当您分配它时,不再需要额外的参考:
mod->_CompArr[mod->_CompCount] = _comp;
第二种选择是完全取消间接。 这可能不太理想,因为它涉及复制数据,但它看起来像这样:
struct Module { Component _CompArr[MAX_COMP_COUNT]; uint8_t _CompCount; };
用法:
if(mod->_CompArr[i]._id == 0xFF)...
和任务:
mod->_CompArr[mod->_CompCount] = *_comp;
另一种选择当然是修复你的编译器错误。 由于优先规则, *(mod->_CompArr[i])->_id
等价于*((mod->_CompArr[i])->_id)
而不是(*(mod->_CompArr[i]))->_id
。 要获得后者,您必须显式包含括号,如图所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.