Pointer initialization during declaration in C structure

Is there a way to initialize a pointer in a C structure during declaration:

struct person
{
  uint8_t age;
  uint16_t * datablock;
} mike = { 2, malloc(4) };

      

I tried the code above, but I get:

The initialization member is not a constant for a data block member.

I am using GCC.

+3


source to share


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







All Articles