user4292309
user4292309

Reputation:

Initializing a pointer at declaration time in a C struct

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

Answers (1)

jfMR
jfMR

Reputation: 24738

How to initialize a struct's member at declaration

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 };

Why does your code not compile?

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.


Alternative to run-time allocation

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

Related Questions