2

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;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
MLAC
  • 129
  • 2
  • 10
  • You can't return a local variable. Read this: http://stackoverflow.com/questions/4824342/returning-a-local-variable-from-function-in-c – Andrew Henle Sep 27 '15 at 17:51
  • Aside: You should call `srand` only once at the beginning of your program. The way you re-seed the random number generator here will cause the function to return the same set of pixels if it is called within the same second of system time. – M Oehm Sep 27 '15 at 17:53
  • 1
    Also, `srand(time(NULL));` will cause rand() to generate the exact same sequence of "random" numbers if your function is called such that `time(NULL)` returns the same value as the previous invocation. Man page is here: http://man7.org/linux/man-pages/man2/time.2.html – Andrew Henle Sep 27 '15 at 17:54

2 Answers2

6

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
3

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.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90