I want to use a struct to store a variable length array of bytes (a UART message) and some other information/flags along with it such as length, what the message does etc. I have a struct defined:
typedef struct Message {
int length;
int otherInfo;
char* bytes;
} Message;
And want to statically allocate an array of these structs which will correspond to certain messages (I have an enum to define the indexes) :
Message messages[] = {
[UART_MESSAGE_TO_DO_X] = {
.length = 16,
.otherInfo = 10,
.bytes = {
0xB5, 0x62, //array of bytes that does X
0x06, 0x01,
0x08, 0x00,
0xF0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0x23
}
},
[UART_MESSAGE_TO_DO_Y] = {
.length = 20,
.otherInfo = 15,
.bytes = {
0xB5, 0x62, //array of bytes that does Y
0x06, 0x41,
0x0C, 0x00,
0x00, 0x00, 0x03, 0x1F, 0xC5, 0x90, 0xE1, 0x9F, 0xFF, 0xFF, 0xFE, 0xFF,
0x45, 0x79
}
}
}
However this gives a warning "excess elements in scalar initializer" which I have looked up and seen solutions where the variable sized array is dynamically allocated and then assigned as a pointer, however I want to statically allocate as the values never change and I am working on a microprocessor with limited resources. I understand that a variable length array where the length isn't known can't be statically allocated, however in my case the length of each array is known and is constant, it is just that the length is not the same between instances of the stuct.
char* bytes;
It's a normal pointer. Allocate the array. Assign the pointer.
static char array[] = {
0xB5, 0x62, //array of bytes that does X
0x06, 0x01,
0x08, 0x00,
0xF0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0x23
};
static Message messages[] = {
[UART_MESSAGE_TO_DO_X] = {
.length = 16,
.otherInfo = 10,
.bytes = array,
},
};
Or with a compound literal https://en.cppreference.com/w/c/language/compound_literal . Watch out for the lifetime of a compound literal.
static Message messages[] = {
[UART_MESSAGE_TO_DO_X] = {
.length = 16,
.otherInfo = 10,
.bytes = (char[]){
0xB5, 0x62, //array of bytes that does X
0x06, 0x01,
0x08, 0x00,
0xF0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0x23
}
},
};
A "variable length array" is a defined term - https://en.cppreference.com/w/c/language/array#Variable-length_arrays . Your arrays seem to be constant in size.
Consider adding const
if all the data are constant.