Error in C for Array: error variably modified -


i error when run code:

"error: invariably modified 'square_toys' @ file scope. 

there variable defined globally @ top of code called numoftoys, , define array toy* square_toys[numoftoys] following after. numoftoys dependent on user inputs cannot define size of array beforehand :( . have suggestions how can rid of error?

int numoftoys; <------- entered through user running programin terminal struct toy * square_toys[numoftoys]; 

you can't use direct array in case. variable length arrays can declared in local scope. i.e. if array size run-time value, cannot declare such array in file scope. arrays static storage duration shall have compile-time sizes. there's no way around it.

if array has declared in file scope (btw, why?), have use pointer instead , allocate memory manually using malloc, in

int numoftoys; struct toy **square_toys;  int main() {   ...   /* when value of `numoftoys` known */   square_toys = malloc(numoftoys * sizeof *square_toys);   ...   /* when no longer need */   free(square_toys);   ... } 

another alternative stop trying use file scope variable , switch local array instead. if array size not prohibitively large, able use variable length array in local scope.

a third alternative ugly hybrid approach: declare global pointer, use local vla allocate memory

int numoftoys; struct toy **square_toys;  int main() {   ...   /* when value of `numoftoys` known */   struct toy *local_square_toys[numoftoys];   square_toys = local_square_toys;   ... } 

but here illustrative purposes. ugly.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -