使用结构内部的 int 变量初始化静态数组

Initializing static array using int variable from inside a struct

我正在使用用于表示图像的 typedef,见此处:

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;

因此,例如一张包含三个像素(一白一蓝一黑)的图像,颜色数组将如下所示:

{
  0xff, 0xff, 0xff,
  0x00, 0x00, 0xff,
  0x00, 0x00, 0x00
}

无论如何,我正在传递一个 Image 实例作为函数中的参数。使用此参数,我尝试使用 colorSize 变量初始化静态数组,作为我维护的唯一变量以跟踪颜色数组的大小。但是我收到一个错误,因为初始化值不是常量。我该如何解决这个问题?

char *foobar( Image *image, ... ) 
{
  static unsigned char arr[image->colorSize];

  ...
}

静态数组不能是可变长度的。使用静态指针来代替动态分配。

char *foobar(Image *image, ...) {
    static unsigned char *arr;
    if (!arr) {
        arr = malloc(image->colorSize);
    }
    ...
}