0

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];

  ...
}
6
  • 3
    Are you sure you're using C99? It has variable-length arrays, so that declaration should be valid. Commented Nov 23, 2019 at 20:32
  • Your title mentions a static array, but your array is not declared static. Commented Nov 23, 2019 at 20:32
  • Yes I am using c99 when compiling with gcc. And yes it's static, left it out by typo lol. Commented Nov 23, 2019 at 20:35
  • 3
    In that case, it's not possible. Static arrays are allocated at program startup time, not when the function is called. Commented Nov 23, 2019 at 20:39
  • 2
    A suggestion: It might be good to tell us what you are really trying to achieve. Why does arr need to be static for example? If you give a fuller picture we may be able to give better suggestions rather than focusing on what may be the wrong way of achieving what you really want to do. Commented Nov 23, 2019 at 20:43

1 Answer 1

2

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);
    }
    ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is this prone to memory leaks and also a bit limiting
@EdHeal Not really, it's using memory the same way a static array would: it lasts until the program ends.
Perfect, that fixed the issue! Thanks for the help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.