1. 程式人生 > >C指標 三維動態陣列建立

C指標 三維動態陣列建立

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>

//create 3D array add init cell 0
int*** createArray3D(int row, int col, int cel)
{
	int *** arr_head = NULL;
	int **  row_head = NULL;
	int *   col_head = NULL;
	int i = 0;

	//init array head
    arr_head = (int***)malloc(sizeof(int**) * row);
	if(arr_head == NULL)
		return 0;

    row_head = (int**)malloc(sizeof(int*) * row * col);
	if(row_head == NULL)
		return 0;

	col_head = (int*)malloc(sizeof(int) * row * col * cel);
	if(col_head == NULL)
		return 0;

	//create row
	for(i =0; i<row; i++)
	{
		arr_head[i]=&(row_head[i*col]);
	}
    //create col
	for(i =0; i<row*col; i++)
	{
		row_head[i]=&(col_head[i*cel]);
	}
    
	//init cells
	for(i =0; i<row*col*cel; i++)
	{
		col_head[i]=0;
		//col_head[i]=rand();
	}

	return arr_head;
}

void distroyArray3D(int*** arr_head)
{
	free(arr_head[0][0]);//free cel
	free(arr_head[0]); //free col
	free(arr_head); //free row
	arr_head = NULL;
}


int _tmain(int argc, _TCHAR* argv[])
{

    int *** arr_head = NULL;

	int i,j,k;
	int row = 4;
	int col = 6;
	int cel = 10;


	arr_head = createArray3D(row, col, cel);
	for(i=0; i<row; i++)
	{
	   for(j=0; j<col; j++)
	   {
		   for(k=0; k<cel; k++)
		   {
		       printf(" vol[%d %d %d]=%d ",i,j,k,arr_head[i][j][k]);

		   }
		   printf("\n");
	   }
	   printf("\n\n");
	}

	distroyArray3D(arr_head);

	system("pause");

	return 0;
}

陣列在記憶體中的儲存順序:以int arr[3][3][3] 為例子,按照下列順序地址遞增

arr[0][0][0] - arr[0][0][2]   //0x0000FFF0 0x0000FFF4 0x0000FFF8 0x0000FFFC
arr[0][1][0] - arr[0][1][2]   //0x00010000 0x00010004 0x00010008 0x0001000C
arr[0][2][0] - arr[0][2][2]    //0x00010010 0x00010014 0x00010018 0x0001001C

arr[1][0][0] - arr[1][0][2]  //...
arr[1][1][0] - arr[1][1][2]
arr[1][2][0] - arr[1][2][2]

arr[2][0][0] - arr[2][0][2]
arr[2][1][0] - arr[2][1][2]
arr[2][2][0] - arr[2][2][2]