简体   繁体   中英

Is there a shorter way to initialize an array of structs?

I have a "buffer of buffers" like this:

#define BUFFER_MESSAGE_COUNT 5

unsigned char buffer_data[BUFFER_MESSAGE_COUNT][128];

typedef struct {
    unsigned char *data;
    int size;
    int cursor;
} t_buffer;

typedef struct {
    int cursor;
    int size;
    t_buffer buffers[BUFFER_MESSAGE_COUNT];
} t_message_buffer;

t_message_buffer message_buffer = {
    0,
    BUFFER_MESSAGE_COUNT,
    {
        { buffer_data[0], sizeof(buffer_data[0]) / sizeof(char), 0 },
        { buffer_data[1], sizeof(buffer_data[1]) / sizeof(char), 0 },
        { buffer_data[2], sizeof(buffer_data[2]) / sizeof(char), 0 },
        { buffer_data[3], sizeof(buffer_data[3]) / sizeof(char), 0 },
        { buffer_data[4], sizeof(buffer_data[4]) / sizeof(char), 0 }
    }
};

Is there a shorter/better way to declare and initialize it than giving all the elements?

I am using the Microchip XC8 compiler, but the question is probably universal.

I assume you are working in an environment where size does matter (for a change).

If it's the case, I'm not quite sure it is an efficient way of initializing a RAM structure.
This will force the compiler to allocate an identical amount of ROM for pre-main static variables initialization.

Since the contents of your structure seems fairly redundant, using an initializer function would likely be more efficient in terms of resource usage, and certainly more readable and evolutive than an initializer macro.

All things being equal, I would simply go for an initializer function.

The method you are using is fine, but it's not very adaptable. A for loop would be better:

t_message_buffer message_buffer;

message_buffer.cursor = 0;
message_buffer.size = BUFFER_MESSAGE_COUNT;
for(int i = 0; i < BUFFER_MESSAGE_COUNT; i++)
{
    message_buffer.buffers[i].data = buffer_data[i];
    message_buffer.buffers[i].size = sizeof(buffer_data[i]);
    message_buffer.buffers[i].cursor = 0;
}

This way, if the value of BUFFER_MESSAGE_COUNT changes, you won't have to adjust many places in the code.

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