Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


1 Answers

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.

like image 195
ネロク・ゴ Avatar answered Jun 08 '26 03:06

ネロク・ゴ