Reputation: 5028
I know how to dynamic allocate a new array with malloc
.
I wonder if there's a way to avoid that in this situation:
#define RX_BUFFER_SIZE 256
#define TX_BUFFER_SIZE 128
typedef struct MyBuffer
{
volatile uint8_t RX[RX_BUFFER_SIZE];
volatile uint8_t TX[TX_BUFFER_SIZE];
volatile uint16_t RX_Head;
volatile uint16_t RX_Tail;
volatile uint16_t TX_Head;
volatile uint16_t TX_Tail;
} MyBuffer_t;
typedef struct MyChannel
{
// other stuff
MyBuffer_t buffer;
} MyChannel_t;
then in my code I create several variables like this:
MyChannel_t ch1;
MyChannel_t ch2;
MyChannel_t ch3;
but I would like to set a different sizes of the arrays for each variable. It's ok to select among a small set, i.e.:
#define RX_BUFFER_SIZE_S 32
#define TX_BUFFER_SIZE_S 16
#define RX_BUFFER_SIZE_M 128
#define TX_BUFFER_SIZE_M 64
#define RX_BUFFER_SIZE_L 256
#define TX_BUFFER_SIZE_L 128
Is there a way to achieve this without using malloc
?
Upvotes: 0
Views: 91
Reputation: 16043
Declare your buffers as pointers:
typedef struct MyBuffer
{
volatile uint8_t * RX;
volatile uint8_t * TX;
size_t rxSize;
size_t txSize;
volatile uint16_t RX_Head;
...
And then use separate static allocation for the buffers, and use them to initialize your object.
volatile uint8_t ch1_rx_buffer[RX_BUFFER_SIZE_S];
volatile uint8_t ch1_tx_buffer[TX_BUFFER_SIZE_S];
MyChannel_t ch1 = {
.buffer = {
ch1_rx_buffer,
ch1_tx_buffer,
sizeof ch1_rx_buffer,
sizeof ch1_tx_buffer,
...
}
}
Upvotes: 2