创建结构数组

标签 c arrays struct

在尝试解决这个问题时,我一直在复制这个问题 How do you make an array of structs in C? 中给出的示例 所以现在我的代码看起来像这样:

#define NUM_TRACES 6

typedef struct 
{
    uint32_t upstream_pin;
    uint32_t dnstream_pin;
    uint32_t led_pin;
}trace;

struct trace traces[NUM_TRACES];

traces[0] = {GPIO_Pin_3, GPIO_Pin_7 , GPIO_Pin_0};
traces[1] = {GPIO_Pin_4, GPIO_Pin_6 , GPIO_Pin_1};

但是我得到以下错误

src/hal.c:17:14: error: array type has incomplete element type
 struct trace traces[NUM_TRACES];
              ^
src/hal.c:19:1: warning: data definition has no type or storage class
 traces[0] = {GPIO_Pin_3, GPIO_Pin_7 , GPIO_Pin_0};

我可以通过使数组成为我认为有意义的跟踪结构的指针数组来修复第一个错误

struct trace* traces[NUM_TRACES];

但是这些行给出了一个错误

src/hal.c:19:1: warning: data definition has no type or storage class
 traces[0] = {GPIO_Pin_3, GPIO_Pin_7 , GPIO_Pin_0};
 ^
src/hal.c:19:1: warning: type defaults to 'int' in declaration of 'traces'
src/hal.c:19:1: error: conflicting types for 'traces'
src/hal.c:17:15: note: previous declaration of 'traces' was here
 struct trace* traces[NUM_TRACES];
               ^
src/hal.c:19:1: warning: excess elements in array initializer
 traces[0] = {GPIO_Pin_3, GPIO_Pin_7 , GPIO_Pin_0};
 ^

我认为这是由于 trace[0] 实际上是存储数据地址的地方,而不是存储数据的地方造成的?但我不知道如何更正此问题并将数据放在数组中我想要的位置。

最佳答案

将结构重写为

struct trace
{
    …
};

您现有代码的问题是您定义了一个匿名结构和一个引用该结构的 trace 的 typedef。这意味着没有类型 struct trace,因此您的行 struct trace traces[NUM_TRACES] 指的是一个不存在的类型。

您也可以将您的结构定义为

typedef struct trace
{
    …
} trace;

如果你愿意,这会给你 tracestruct trace,但实际上没有任何意义。

当然,您可以保留当前类型,只说trace traces[NUM_TRACES]


您的代码行 traces[0] = {GPIO_Pin_3, GPIO_Pin_7 , GPIO_Pin_0 }; 也不正确。编译器将其解释为没有类型的零长度数组的声明。如果您想初始化 traces 数组,您必须在实际的初始化程序中进行,如

struct trace traces[NUM_TRACES] = { {GPIO_Pin_3, GPIO_Pin_7 , GPIO_Pin_0} };

(如果 NUM_TRACES 大于 1 这将使数组的其余部分保持零初始化)

关于创建结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46123299/

相关文章:

c - 是否允许变量数组参数作为函数外的索引变量?

java - 在嵌套循环中填充数组

c - 如何根据打印的数组增加计数器

c++ - 复制结构时出现 System.AccessViolationException

受控嵌套循环

c - 如何检查void指针是否指向任意低地址?

c - 需要帮助为数组的结构数组分配内存

c++ - 从基于两个变量的结构 vector 中获取 min_element

比较 2 个字符串,一个在结构中,另一个不是 C 编程

c - 如果多个线程并行处理,如何维护数据包的顺序?