簡體   English   中英

您如何在C中動態分配連續的3D數組?

[英]How do you dynamically allocate a contiguous 3D array in C?

在C語言中,我想按此順序遍歷數組

 for(int z = 0; z < NZ; z++)
    for(int x = 0; x < NX; x++)
       for(int y = 0; y < NY; y++)
           3Darray[x][y][z] = 100;

我如何以這種方式創建此數組,使3Darray [0] [1] [0]在內存中的3Darray [0] [2] [0]之前出現?

我可以進行初始化,使我獲得“ z-主要”排序,但是我真的想要此3d數組的y-主要排序

這是我一直在嘗試使用的代碼:

char *space;
char ***Arr3D;
int y, z;
ptrdiff_t diff;



space = malloc(X_DIM * Y_DIM * Z_DIM * sizeof(char))

Arr3D = malloc(Z_DIM * sizeof(char **));

for (z = 0; z < Z_DIM; z++)
{
    Arr3D[z] = malloc(Y_DIM * sizeof(char *));

    for (y = 0; y < Y_DIM; y++)
    {
        Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM);
    }
}

您不能更改語言隱式的數組順序。 數組排序是C語言的標准配置。

如果要更改排序方式,只需更改訪問數組的方式,即: [x][z][y]而不是[x][y][z]

我認為這樣做的唯一方法是在連續的數據存儲上編寫自己的上/下卷功能。 換句話說,您將必須編寫自己的映射來計算值的存儲位置。

如果您想使數組的特定順序遍歷更有效,則始終可以在將傳入矩陣放入數組之前對其進行變換,然后在取出矩陣時再次進行變換。 C風格的多維數組是按順序排列的,因此數學運算可能會有些棘手(並且超出了我在此處所能詳述的范圍)。

抱歉,沒有更好的答案,但希望對您有所幫助

使用指針數組可以加快處理速度,但會帶來更大的復雜性。 如果不確定是否需要性能,則可以嘗試使用C宏:

#define ARR3D(x,y,z) space[(x) + XDIM*((y) + Y_DIM*(z))]

假設x,y和z分別是最里面,最中間和最外面的尺寸。

偽代碼:

malloc a chunk of memory big enough for
   the char *** pointer for z,
   the char ** pointers for y, which will get pointed to by zs
   the char * pointers for x, which will get pointed to by ys
   the big block of data that they will, in the end, be pointed to by xs
assign z's, y's, x's so that 
    contiguous blocks from the big block of data are adjacent in the y dimension
    (instead of adjacent in the x dimension, as would be normal)

我已經完成了2D數組的single-malloc技巧,這僅僅是因為精神鍛煉以及單個malloc / single free的附加便利性,並且它的運行效果非常好(只需確保獲得一個對齊良好的內存塊即可)。 我從沒想過要用它來破壞內存鄰接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM