繁体   English   中英

C结构中的可变2D数组

[英]Variable 2D array in a C struct

这可能是一个简单答案的问题,但是我没有找到合适解决方案的类似问题。 我试图创建一个struct用C,其具有两个变量,然后二维阵列,其尺寸等于用于创建两个可变参数的struct

struct image{
  int width;
  int hight;
  int pixles[width][height];
};

现在,我什至在编译之前就知道这是行不通的,但是我不确定如何进行这项工作。

您不能像在评论中所说的那样直接这样做。 有两种常用的惯用法来模拟它(假设支持VLA):

  1. 您只在结构中存储指向(动态分配的)数组的指针,然后将其强制转换为指向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]; 
  2. 如果动态分配结构,则可以使用大小为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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM