SevenCode
SevenCode

Reputation: 3

error: variable-sized object may not be initialized|

My code as bellow:

const size_t NUM_P = 100;
int main (viod)
{
   char *pS[NUM_P] = { NULL};            /* Array of string pointer */
   /* Other code */
}

My compiler is CODEBLOCK, the error will be clear when NUM_P is changed to digits, such as "12,or 35 ..", I don't know the root cause of the error , or it is my compiler problem.

Upvotes: 0

Views: 299

Answers (3)

rems4e
rems4e

Reputation: 3172

The root of your problem is that NUM_P is a variable, even if it is a const one.

Replace its declaration by #define NUM_P 100 and your code will compile again.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206657

That's valid in C++ but not in C. You can use a preprocessor symbol to do that in C.

#define NUM_P 100
int main (viod)
{
   char *pS[NUM_P] = { NULL};
}

Upvotes: 0

M.M
M.M

Reputation: 141618

In C you are not allowed to provide an initializer for VLAs.

I'd suggest using a compile-time constant for the array dimension; then it is not a VLA:

#define NUM_P 100

int main(void)
{  
    char *pS[NUM_P] = { 0 };
}

For historical reasons, a const variable is not considered to be a constant expression in C.

Upvotes: 1

Related Questions