I tried to write a function that returns a random array of pixel colors, so when I call randomPalette(i)
, the function will create a random array of i
colors. Below are my codes. It says error at random[colors]
that expression must have constant value. I don't know why. How to fix it?
pixel* randomPalette(int colors){
pixel random[colors] ;
int i, x;
srand(time(NULL)); //generate a random seed
for (i = 0; i < colors; i++){
x = rand() % 256;
random[i].r = x; random[i].g = x; random[i].b = x;
}
return random;
}
In your code, firstly
pixel random[colors] ;
syntax is called variable length array a.k.a VLA and only supported on and over C99
. If you want this to work, you need to enforce your compiler to use C99
mode, like for gcc
, you'll need to use --std=C99
compiler option.
Secondly, random
is an automatic local variable and you're trying to return
(the address of) it. If the returned value is being used, you'll invoke undefined behavior.
Solution: use a pointer and dynamic memory allocation, like malloc()
and family. Dynamically allocated memory lifetime remains alive until deallocated manually by calling free()
, so you can return the pointer from the function and use it in the caller, too.
Below are my codes. It says error at random[colors] that expression
must have constant value. I don't know why. How to fix it?
Apparently you don't have support for variable length arrays. Either use a fixed integer (such as #define
or const integer) below instead of colors
:
pixel random[colors] ;
or allocate memory dynamically. e.g.
pixel *random = malloc (sizeof(pixel) * colors);
But don't forget to free
if you use approach as above.
Finally, you can't do this either:
return random;
because you are returning address to local variable which will go out of scope when function ends. Actually, you can return random
if you initialize it using dynamic memory allocation such as with malloc
. But if you don't use dynamic memory you can't return that.