简体   繁体   English

如何在C中声明结构数组

[英]How to declare array of structs in C

I am having trouble declaring an array of structs prior to populating them with data. 在用数据填充结构之前,我很难声明一个结构数组。

My struct looks like this: 我的结构看起来像这样:

typedef struct {
  uint8_t * p_data;     ///< Pointer to the buffer holding the data.
  uint8_t   length;     ///< Number of bytes to transfer.
  uint8_t   operation;  ///< Device address combined with transfer direction.
  uint8_t   flags;      ///< Transfer flags (see @ref NRF_TWI_MNGR_NO_STOP).
} nrf_twi_mngr_transfer_t;

And in my code I am trying to declare the array like this: 在我的代码中,我试图像这样声明数组:

struct nrf_twi_mngr_transfer_t start_read_transfer[10];

However I get a compile error: 但是我得到一个编译错误:

array type has incomplete element type 'struct nrf_twi_mngr_transfer_t' 数组类型的元素类型'struct nrf_twi_mngr_transfer_t'不完整

I have searched around as I thought should be a common thing, but I can't figure out what I am doing wrong. 我进行了搜索,因为我认为这应该很普通,但是我无法弄清楚自己在做什么错。 Maybe because one of the elements is a pointer? 也许因为其中一个元素是指针? But that pointer should be a fixed size right? 但是那个指针应该是固定大小的吧?

Many thanks 非常感谢

It looks like some explanations are in order. 看起来有些解释是适当的。 This code 这段代码

typedef struct {
    //...
} nrf_twi_mngr_transfer_t;

Already defines a type which can be used directly. 已经定义了可以直接使用的类型 In contrast, 相反,

struct nrf_twi_mngr_transfer_struct {
    //...
};

Would define a struct name, and to access it you'd need to indicate that you are referring to a struct. 将定义一个结构名称,要访问它,您需要指出您正在引用一个结构。

As a result, given two definitions above, you should define your arrays differently: 因此,鉴于以上两个定义,您应该以不同的方式定义数组:

nrf_twi_mngr_transfer_t arr[10]; // if using typedef
struct nrf_twi_mngr_transfer_struct arr2[10]; // if using struct with no typedef

And just in case you are wondering, 万一您想知道,

struct {
    //...
} nrf_twi_mngr_transfer_obj;

Defines an object of anonymous struct type. 定义一个匿名结构类型的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM