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

我正在使用用于表示图像的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,0x00,0x00
}

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

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

  ...
}
suse119 回答:从结构内部使用int变量初始化静态数组

静态数组不能为可变长度。而是使用带有静态指针的动态分配。

char *foobar(Image *image,...) {
    static unsigned char *arr;
    if (!arr) {
        arr = malloc(image->colorSize);
    }
    ...
}
本文链接:https://www.f2er.com/3044162.html

大家都在问