簡體   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