简体   繁体   中英

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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