Reputation: 3
I'm working with a typedef used to represent an image, seen here:
typedef struct {
int rows; // Vertical height of image in pixels //
int cols; // Horizontal width of image in pixels //
unsigned char *color; // Array of each RGB component of each pixel //
int colorSize; // Total number of RGB components, i.e. rows * cols * 3 //
} Image;
So for example an image with three pixels, one white, one blue and one black, the color array would look like this:
{
0xff, 0xff, 0xff,
0x00, 0x00, 0xff,
0x00, 0x00, 0x00
}
Anyway, I'm passing an instance of Image as a parameter in a function. With this parameter I'm trying to initialize a static array using the colorSize variable as its the only variable I am maintaining to track the size of the color array. However I'm getting an error because the initialization value is not constant. How might I get around this?
char *foobar( Image *image, ... )
{
static unsigned char arr[image->colorSize];
...
}
Upvotes: 0
Views: 43
Reputation: 781004
Static arrays cannot be variable-length. Use dynamic allocation instead, with a static pointer.
char *foobar(Image *image, ...) {
static unsigned char *arr;
if (!arr) {
arr = malloc(image->colorSize);
}
...
}
Upvotes: 2