【发布时间】:2021-07-22 19:17:12
【问题描述】:
我会尽我所能解释这一点。 我已经在 C 领域工作了一段时间,但从来不需要超越我的舒适区。我真的很想尝试让它发挥作用,这将有助于维护我一直在努力工作的程序结构。
虽然我没有接受过正式的 C 培训,所以我会尽可能多地自学。
我有一个 typedef 结构,我们称之为“struct_A_t”,另一个 typedef 结构“struct_B_t”。在“struct_A_t”中,我想要(除其他外)一个指向“struct_B_t”数组的成员。我有多个“struct_A_t”实例,它们的“struct_B_t”项的数组长度并不相同。
我知道将数组传递给 fn 会将地址传递给第一个元素,但我也注意到指向数组的指针和指向第一个元素的指针不一定相同。不过,一些指针的东西仍然让我着迷。
理想的情况是我能够将“struct_A_t”项的所有实例放入一个数组中,并在我的程序中传递这个数组,根据需要更改 struct_B 和 struct_A 成员的值。
参见下面的示例代码:
我的 main.h
#include <stdio.h>
#include "stdlib.h"
#include "stdbool.h"
#include "stdint.h"
//Defines fo the array lengths of struct_B_t
#define MyGroup0_Length 10
#define MyGroup1_Length 20
#define MyGroup2_Length 30
#define GroupCount 3
//Struct B definition
typedef struct
{
bool ItemSelected;
uint8_t ItemID;
uint8_t ItemState;
} struct_B_t;
//Struct A Definition
typedef struct
{
bool GroupEnabled;
uint8_t GroupID;
uint8_t GroupState;
uint8_t ItemCount;
struct_B_t (*ItemList)[];
} struct_A_t;
//These are the item lists that must be contained within each GroupState
struct_B_t Group0Items[MyGroup0_Length];
struct_B_t Group1Items[MyGroup1_Length];
struct_B_t Group2Items[MyGroup2_Length];
//Function prototypes
void main(void);
void BuildGroups(struct_A_t* _groups);
void ChangeGroupItems(struct_A_t* _groups, uint8_t _groupCount);
我的 main.c
#include <stdio.h>
#include "stdlib.h"
#include "stdint.h"
#include "stdbool.h"
#include "main.h"
//A array of type "struct_A_t" with length = 3, to accomodate my three groups
struct_A_t MyGroups[GroupCount];
void main(void)
{
BuildGroups(&MyGroups);
ChangeGroupItems(&MyGroups, GroupCount);
}
void BuildGroups(struct_A_t* _groups)
{
//Set the group lists
//Group 1
_groups[0].ItemList = &Group0Items;
_groups[0].ItemCount = MyGroup0_Length;
//Group 2
_groups[1].ItemList = &Group1Items;
_groups[1].ItemCount = MyGroup1_Length;
//Group 3
_groups[2].ItemList = &Group2Items;
_groups[2].ItemCount = MyGroup2_Length;
}
void ChangeGroupItems(struct_A_t* _groups, uint8_t _groupCount)
{
for(uint8_t i = 0; i < _groupCount; i++)
{
for(uint8_t j = 0; j < _groups[i].ItemCount; j++)
{
if(_groups[i].ItemList[j].ItemSelected)
{
_groups[i].ItemList[j].ItemState++;
}
}
}
}
您可以猜到,这没有正确编译。当我稍微改变一下并构建它时,我会收到不兼容指针类型的警告。
我不觉得这是一个非常独特的问题,所以我很想听听任何建议。 在这个阶段,我试图将我的应用程序数据限制在一个结构中,并且我想避免让太多的东西全局可访问。
我还应该注意,我的实际程序看起来有点不同,并且事情被分成比这更多的 .c 文件,而我想要实现的目标将很好地适应我的整体程序模式。
提前致谢。
【问题讨论】:
-
struct_B_t *ItemList和_groups[0].itemList = Group0Items; -
用
struct_B_t *ItemList;替换struct_B_t (*ItemList)[]; -
您在研究微控制器吗?如果有,是哪一个?不一定与该问题相关,但
void main(void)不应在托管环境中使用。那和您对uint8_t的使用让您认为您处于独立环境中? -
@12431234123412341234123 名字不要以
_开头,它们是保留的。仅C标准完全reserves identifiers that start with two underscores or one underscore and a capital letter。单下划线后跟小写字母可以作为局部变量或函数参数。永远不要使用下划线开头的变量确实可以更容易地避免潜在的冲突。 -
您好,感谢您的回复。我正在 stm32 上开发一个自定义项目。如果我要替换 struct_B_t itemlist 定义,我仍然可以将它作为数组使用和访问吗?感谢您的提示,我正在快速尝试启动并运行一个工作示例,但肯定会注意到这一点以供将来参考。