【问题标题】:Variable 2D array in a C structC结构中的可变二维数组
【发布时间】:2017-02-27 01:37:28
【问题描述】:
这可能是一个答案很简单的问题,但我没有找到任何类似的解决方案。我正在尝试在 C 中创建一个 struct,它有两个变量,然后是一个二维数组,其维度等于用于创建 struct 的两个变量参数的维度。
struct image{
int width;
int hight;
int pixles[width][height];
};
现在我什至在编译之前就知道这行不通,但我不知道如何去做。
【问题讨论】:
标签:
c
arrays
struct
2d
dynamic-arrays
【解决方案1】:
您不能像 cmets 中所说的那样直接执行此操作。 模拟它有两种常见的习语(假设支持 VLA):
-
您只在结构中存储一个指向(动态分配的)数组的指针,然后将其转换为指向 2D VLA 数组的指针:
typedef struct _Image {
int width;
int height;
unsigned char * data;
} Image;
int main() {
Image image = {5, 4};
image.data = malloc(image.width * image.height);
unsigned char (*data)[image.width] = (void *) image.data;
// you can then use data[i][j];
-
如果动态分配结构,可以使用大小为 0 的数组作为其最后一个元素(并再次将其转换为 VLA 指针):
typedef struct _Image {
int width;
int height;
unsigned char data[0];
} Image;
int main() {
Image *image = malloc(sizeof(Image) + 5 * 4); // static + dynamic parts
image->width = 5;
image->height = 4;
unsigned char (*data)[image->width] = (void *) &image->data;
// you can then safely use data[i][j]
如果您的 C 实现不支持 VLA,您必须恢复到通过 1D 指针模拟 2D 数组的旧习惯用法:data[i + j*image.width]