1

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?

mahmood
  • 23,197
  • 49
  • 147
  • 242
  • 2
    Does this answer your question? [Initializer element is not a constant](https://stackoverflow.com/questions/14902456/initializer-element-is-not-a-constant) – kaylum Mar 06 '22 at 11:28

1 Answers1

3

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 ) );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335