Pointer initialization during declaration in C structure
1 answer
How to initialize a struct member on declaration
You can initialize the members of a structure when you declare it using a compile-time constant, as in the code below:
struct person
{
uint8_t age;
uint16_t * datablock;
} mike = { 2, NULL };
Why won't your code compile?
malloc(4)
is a function call and it will be executed at runtime. Thus, the error message you receive is pretty accurate.
Alternative to scheduling runtime
You could do something like this:
#define NUM 2 // change NUM at will
static uint16_t data[NUM]; // memory that will be allocated
struct person
{
uint8_t age;
uint16_t * datablock;
} mike = { 2, data };
Note that in this case the address data
is known at compile time, so you can use it as an initializer for the structure members.
+5
source to share