-1

My question is very basic, but I couldn't find anything about it. I have an array of pointers. I want to assign it like this

mat* quickAccessMatrices[6] = {&MAT_A,&MAT_B,&MAT_C,&MAT_D,&MAT_E,&MAT_F};

with MAT_A,MAT_B,...,MAT_F being variables of type mat, which is a structure defined elsewhere. this gives a warning when using -pedantic flag, saying

initializer element is not computable at load time

so I think it means I shouldn't do it.

Is there a way to do something like this:

mat* quickAccessMatrices;
quickAccessMatrices = {&MAT_A,&MAT_B,&MAT_C,&MAT_D,&MAT_E,&MAT_F};

just without it giving an error?

Or do I just need to assign it values slot by slot?

By the way, since people were asking, here is how I define mat

typedef struct mat {
        double matrix[4][4];
} mat;

I am well aware this isn't that good, but it is necessary in my case To be clear, I know that I can use normal assignment after the definition, but I'm asking if there is a better way.

PlainXYZ
  • 126
  • 1
  • 8

1 Answers1

1

In this declaration the declared variable is a scalar object

mat* quickAccessMatrices = {&MAT_A,&MAT_B,&MAT_C,&MAT_D,&MAT_E,&MAT_F};

but you are trying to initialize it with a braced list of several initializers as an array.

You could declare an array as

mat* quickAccessMatrices[] = {&MAT_A,&MAT_B,&MAT_C,&MAT_D,&MAT_E,&MAT_F};

Or you could declare a pointer of the type mat ** and initialize it with a compound literal like

mat** quickAccessMatrices = ( mat *[] ) { &MAT_A,&MAT_B,&MAT_C,&MAT_D,&MAT_E,&MAT_F};

As for this warning

initializer element is not computable at load time

when you may not initialize arrays in file scope with non-constant expressions. So declare the array or the pointer to the compound ;literal in a function for example in main.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335