0

When I tried to initialize a global array that contains structure elements, I got the " error: initializer element is not constant"

a.h


#define MAX_MSG_NUM 20
#define NAME_SIZE   15
#define MAX_QUE_NUM  10

typedef struct {
   int         index;
   int         tid;
   int         front;
   int         rear;
   char        name[NAME_SIZE];
   char        msgbuf[MAX_MSG_NUM];
} THREAD;

typedef enum {
   I1        = 0,
   I2        = 1,
   I3        = 2,
   I4        = 3
} DMTHREAD;

a.c


THREAD   a[MAX_MSG_NUM];
THREAD   b[MAX_MSG_NUM];
THREAD   c[MAX_MSG_NUM];

THREAD   T[MAX_QUE_NUM] = {
   {I1,   0, 0, 0, "CONFIG1",      a[MAX_MSG_NUM]},
   {I2,   0, 0, 0, "CONFIG2",      b[MAX_MSG_NUM]},
   {I3,   0, 0, 0, "CONFIG3",       c[MAX_MSG_NUM]},
   0
};

GCC compiler.

bash-3.2$ gcc -g a.h a.c
a.c:8: error: initializer element is not constant
a.c:8: error: (near initialization for 'T[0].msgbuf[0]')
a.c:9: error: initializer element is not constant
a.c:9: error: (near initialization for 'T[1].msgbuf[0]')
a.c:10: error: initializer element is not constant
a.c:10: error: (near initialization for 'T[2].msgbuf[0]')

Thanks for help.

Enlightened by your answers, I changed the code and it works fine now.

MSG   T[MAX_QUE_NUM] = {
           {I1,   0, 0, 0, "CONFIG1",      {0}},
           {I2,   0, 0, 0, "CONFIG2",      {0}},
           {I3,   0, 0, 0, "CONFIG3",      {0}}, 
           0,
    }

Thank you for your answers.

3 Answers 3

3

a[MAX_MSG_NUM] is indeed non-constant. It also denotes a Thread instance, which happens to be outside the array you defined earlier, and does not match the type you should pass there (char[]).

So it is wrong on so many levels.

Sign up to request clarification or add additional context in comments.

1 Comment

You are right, I posted wrong code here, sorry. Thread was supposed to be replaced by a self-defined type MSG.
2

You're trying to assign a value that isn't knowable to the compiler at compile time but knows at run time - this is why it's causing the error.

try doing it in main for example:

main(){
  THREAD   T[MAX_QUE_NUM] = {
     {I1,   0, 0, 0, "CONFIG1",      a[MAX_MSG_NUM]},
     {I2,   0, 0, 0, "CONFIG2",      b[MAX_MSG_NUM]},
     {I3,   0, 0, 0, "CONFIG3",       c[MAX_MSG_NUM]},
     0
  };
}

Comments

2

In C, objects with static storage duration such as objects declared at file scope can only be initialized with constant expressions.

For example (declared at file scope):

char bla[] = {1, 2, 3, 4};  // correct
int a = 1;
char blop[] = {a, a + 1};   // incorrect, a is not a constant in C

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.