2017-02-27 66 views
0

這可能是一個簡單答案的問題,但我沒有找到任何類似於它的解決方案。我試圖在C中創建一個具有兩個變量的struct,然後創建一個尺寸等於用於創建struct的兩個可變參數尺寸的二維數組。C結構中的變量二維數組

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

現在我知道這不工作之前,我甚至編譯它,但我不知道如何去做這項工作。

+0

使用指針爲一維數組和2級分配。 – Olaf

+1

這是不可能的;在編譯時必須知道結構體的大小。 –

+0

引用此:http://stackoverflow.com/questions/5170525/array-in-c-struct – kr1tzb1tz

回答

0

你不能像你在評論中所說的那樣直接做到這一點。有到兩種常見的成語模擬(假定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] 
    

如果VLA不會被你的C實現支持,必須恢復到通過1D指針模擬二維數組的老成語:data[i + j*image.width]