Home > Net >  Compilation error for defining static array with pointers
Compilation error for defining static array with pointers

Time:03-07

When I define an array like

double *first = (double *)malloc( N*N*sizeof( double ) );

There is not problem. But when I specify

static double *first = (double *)malloc( N*N*sizeof( double ) );

I get this error

error: initializer element is not constant
   10 |     static double *first = (double *)malloc( N*N*sizeof( double ) );
      |                            ^

How can I fix that?

CodePudding user response:

You may initialize objects with static storage duration with constant expressions. And an expression with a call of malloc is not a constant expression.

So you need for example initialize the pointer as a null pointer like for example

static double *first = NULL;

and then call the function malloc in a function

if ( first == NULL ) first = (double *)malloc( N*N*sizeof( double ) );
  • Related