Reputation:
Is there a way to initialize a pointer in a C struct at declaration time:
struct person
{
uint8_t age;
uint16_t * datablock;
} mike = { 2, malloc(4) };
I've tried the code above, but I get:
initializer element is not constant for the datablock member.
I'm using GCC.
Upvotes: 3
Views: 159
Reputation: 24738
You can initialize the members of the struct at its declaration by means of a compile-time constant as in the code below:
struct person
{
uint8_t age;
uint16_t * datablock;
} mike = { 2, NULL };
malloc(4)
is, however, a function call and it will be performed at run-time. Therefore, the error message you are getting is quite accurate indeed.
You could however 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 of data
is known at compile time, so you can use it as an initializer for the struct's members.
Upvotes: 4