简体   繁体   中英

Error in C for Array: error variably modified

I get this error when I run my code:

"error: invariably modified 'Square_Toys' at file scope.

There is a variable defined globally at the top of my code called NumOfToys , and then I define my array Toy* Square_Toys[NumOfToys] following it after. The NumOfToys is dependent on what the user inputs so I cannot define the size of the array beforehand :( . Does anyone have any suggestions how I can get rid of this error?

int NumOfToys; <------- This is entered through the user running the programin the terminal
struct toy * Square_Toys[NumOfToys];

You can't use a direct array in that case. Variable Length Arrays can only be declared in local scope. Ie if the array size is a run-time value, then you cannot declare such array in file scope. All arrays with static storage duration shall have compile-time sizes. There's no way around it.

If your array has to declared in file scope (BTW, why?), you have to use a pointer instead and allocate memory manually using malloc , as in

int NumOfToys;
struct toy **Square_Toys;

int main()
{
  ...
  /* When the value of `NumOfToys` is already known */
  Square_Toys = malloc(NumOfToys * sizeof *Square_Toys);
  ...
  /* When you no longer need it */
  free(Square_Toys);
  ...
}

Another alternative would be to stop trying to use a file scope variable and switch to a local array instead. If the array size is not prohibitively large, you will be able to use Variable Length Array in local scope.

A third alternative would be an ugly hybrid approach: declare a global pointer, but use a local VLA to allocate the memory

int NumOfToys;
struct toy **Square_Toys;

int main()
{
  ...
  /* When the value of `NumOfToys` is already known */
  struct toy *Local_Square_Toys[NumOfToys];
  Square_Toys = Local_Square_Toys;
  ...
}

But this is here just for illustrative purposes. It is ugly.

Size of global array should be constant because the compiler needs to know it in compile time. If you need a dynamic array, allocate it with malloc in runtime:

Toy **Square_Toys;

void foo(void) {
  Square_Toys = malloc(NumOfToys * sizeof(Toy*));

  // do stuff here

  free(Square_Toys);
}

The NumOfToys is dependent on what the user inputs so I cannot define the size of the array beforehand

Either You can dynamically allocate space for array or use VLA's. For VLA, after user input for NumOfToys declare your array in main .

printf("Enter number of toys: ");
scanf("%d", &NumOfToys);

struct toy * Square_Toys[NumOfToys];    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM