My issue is fairly straightforward. I am trying to initialize the struct in my main function but I get the following error:
$ gcc main2.c -o main2
main2.c: In function ‘main’:
main2.c:39:28: error: initializer element is not constant
.smth.array = (mylib_B_t)
^
main2.c:39:28: note: (near initialization for ‘C.smth.array’)
I tried multiple different ways, yet nothing seems to work. Could someone tell me what I am doing incorrectly? Below is the code in question:
#include <stdio.h>
typedef struct mylib_A_t mylib_A_t;
typedef struct mylib_B_t mylib_B_t;
typedef struct mylib_C_t mylib_C_t;
typedef enum
{
TYPE_A = 0,
TYPE_B = -1
} lib_type_t;
struct mylib_A_t
{
lib_type_t type;
int d;
};
struct mylib_B_t
{
int c;
const mylib_A_t *size;
};
struct mylib_C_t
{
union
{
int b;
mylib_B_t array;
} smth;
};
int main (int argc, char * argv[])
{
static const mylib_C_t C=
{
.smth.array = (mylib_B_t)
{
.c = 66,
.size = &(mylib_A_t)
{
.type = TYPE_A,
.d = 0
}
}
};
return 0;
}
fieldin the error message? It is not in the source code.fieldwithsmth.arrayin your MCVE.The address of a memory object is not considered a constant expression. For static memory objects you need constant initializers. The problem is this line then:.size = &(mylib_A_t). MakeCnon static or initialize.sizeduring runtime. Alsosizeis a very strange name for a pointer....const mylib_A_t *size;