2010-02-03 61 views
0

我正在通過網絡尋找動態分配3D矩陣空間的方法,比如int類型。 而我發現很多網站涉及2D矩陣,這一個 http://www.taranets.com/cgi/ts/1.37/ts.ws.pl?w=329;b=286 而且有這樣的例子如下所示。 我明白所有上面的例子,但是這個關於3D我不能。創作者是以向後的方式分配空間還是還有其他內容? 他開始爲整個矩陣分配空間,然後進入Z軸?那是我無法理解的。C三維數組動態內存分配,問題,需要幫助

此外,如果你知道任何關於此的好網站,請在此發佈,我們將不勝感激。

/* Program 9.4 from PTRTUT10.HTM 6/13/97 */ 
// http://www.taranets.com/cgi/ts/1.37/ts.ws.pl?w=329;b=286 

#include <stdio.h> 
#include <stdlib.h> 
#include <stddef.h> 

int X_DIM=16; 
int Y_DIM=5; 
int Z_DIM=3; 

int main(void) 
{ 
    char *space; 
    char ***Arr3D; 
    int y, z; 
    ptrdiff_t diff; 

    /* first we set aside space for the array itself */ 

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

    /* next we allocate space of an array of pointers, each 
     to eventually point to the first element of a 
     2 dimensional array of pointers to pointers */ 

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

    /* and for each of these we assign a pointer to a newly 
     allocated array of pointers to a row */ 

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

     /* and for each space in this array we put a pointer to 
      the first element of each row in the array space 
      originally allocated */ 

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

    /* And, now we check each address in our 3D array to see if 
     the indexing of the Arr3d pointer leads through in a 
     continuous manner */ 

    for (z = 0; z < Z_DIM; z++) 
    { 
     printf("Location of array %d is %p\n", z, *Arr3D[z]); 
     for (y = 0; y < Y_DIM; y++) 
     { 
      printf(" Array %d and Row %d starts at %p\n", z, y, Arr3D[z][y]); 
      diff = Arr3D[z][y] - space; 
      printf(" diff = %d ",diff); 
      printf(" z = %d y = %d", z, y); 
     } 
     putchar('\n'); 
    } 
    putchar('\n'); 
    system("PAUSE"); 
    return 0; 
} 

回答

4

空間確實是分配給整個矩陣的內存。

然而,他繼續創造指針定位在空間領域與

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

Arr3D的目的只是通過索引(指定Z,Y,X索引)訪問空間的方式。空間只有一個索引,所以如果您想通過空間訪問矩陣元素[a][b][c],則需要將其轉換爲單個space[d],其中d與a*Y_DIM*Z_DIM + b*Z_DIM+c類似。因此,通過Arr3D,您可以訪問[a][b][c]Arr3D[a][b][c]

Arr3D本身是一個數組char**,它們是指向char類型指針的指針。 Arr3D[z]然後是指向一個char指針數組的指針。每個Arr3D[z][y]然後設置爲指向原來的3x3矩陣的特定行與

Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM); 

因此然後用Arr[1][2]你再訪問行與矩陣的z=1, y=2

+0

對。這裏的基本概念是'space'指向實際的3D數組,平鋪成一維數組,並且'Arr3D'被設置爲該數組的索引 - 它只是使訪問更方便。 – caf 2010-02-03 22:26:58

+0

現在有點清楚了,我明白這是如何工作的,但是我仍然無法用ZYX顯示訪問反向3D數組。 這個例子更適合我: http://stackoverflow.com/questions/1824363/dynamic-allocation-deallocation-of-2d-3d-arrays。 對於像我這樣的初學者來說更有意義。 感謝威爾和其他人的幫助! – 2010-02-04 17:30:09

0

該示例應該做的是將更高維度指向已分配的連續塊。

+0

這就是它所做的... – 2010-02-04 06:49:50