简体   繁体   中英

Variable 2D array in a C struct

This is probably a question with a simple answer but I am not finding anything similar to it with a proper solution. I am trying to create a struct in C that has two variables and then a two dimensional array with dimensions equal to that of the two variable parameters used to create the struct .

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

Now I knew this wouldn't work before I even compiled it but I'm not sure how to go about making this work.

You cannot do that directly as you were said in comments. There are two common idioms to simulate it (assuming VLA are supported):

  1. you only store in the struct a pointer to a (dynamically allocated) array, then you cast it to a pointer to a 2D VLA array:

     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. If you dynamically allocate the structs, you can use an array of 0 size as its last element (and again cast it to a VLA pointer):

     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] 

If VLA are not supported by your C implementation, you must revert to the old idiom of simulating a 2D array through a 1D pointer: data[i + j*image.width]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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