variably modified array at file scope in C

I have some code like this:

static int a = 6;
static int b = 3;

static int Hello[a][b] =
{
    { 1,2,3},
    { 1,2,3},
    { 1,2,3},
    { 1,2,3},
    { 1,2,3},
    { 1,2,3}
};

but when I compile it, it says error:

variably modified 'Hello' at file scope

how could this happen? and how could I fix it?


Solution 1:

You can not have static array which size is given as a variable

That's why constants should be #defined:

#define a 6

This way preprocessor will replace a with 6, making it valid declaration.

Solution 2:

Simple answer variable modified array at file scope is not possible.

Detailed :

make it compile time integral constant expression, since array length must be specified at the compile time.

like this :

#define a 6
#define b 3

Or, follow c99 standard. and compile like for gcc.

gcc -Wall -std=c99 test.c -o test.out

The problem here is variable length array with providing length may not be initialized so you are getting this error.

simply

static int a =6;
static int b =3;

void any_func()
{
int Hello [a][b]; // no need of initialization no static array means no file scope.
}

Now use for loop or any loop to fill the array.

For more info just a DEMO :

#include <stdio.h>
static int a = 6; 
int main()
{
int Hello[a]={1,2,3,4,5,6}; // see here initialization of array Hello it's in function
                            //scope but still error
return 0;
}


root@Omkant:~/c# clang -std=c99 vararr.c -o vararr
vararr.c:8:11: error: variable-sized object may not be initialized
int Hello[a]={1,2,3,4,5,6};
          ^
1 error generated. 

If you remove static and provide initialization then it will generate error as above.

But if you keep static as well as initialization the still will be error.

But if you remove initialization and keep static the below error will come.

error: variable length array declaration not allowed at file scope
static int Hello[a];
           ^     ~
1 error generated.

So variable length array declaration not allowed at file scope so make it function or block scope inside any function (but remember making it function scope must remove initialization)

NOTE : Since it's C tagged so making a and b as const won't help you but in C++ const will work fine.