C語言中動態申請連續的二維數組

      可以採用多申請一些指針,然後這一些指針分別指向後面數據區中對應的位置,如一個3*4int類型數組,我們先申請大小爲sizeof(int*) * 3 + 3 * 4 * sizeof(int)的一維數組設爲arr。然後arr[0]存放指向arr + sizeof(int*) * 3這個位置的指針,arr[1]存放指向arr + sizeof(int*) * 3 + 4 * sizeof(int)這個位置的指針, arr[2]存放指向arr + sizeof(int*) * 3 + 2 * 4 * sizeof(int)這個位置的指針

代碼如下:
#include "StdAfx.h"
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h> 

// BYTE型顏色:RGB
typedef unsigned char  BYTE;
typedef struct tagBYTECOLORRGB
{
	BYTE red;
	BYTE green;
	BYTE blue;
}BYTECOLORRGB;

//動態申請二維數組  
template <typename T>  
T** malloc_Array2D(int row, int col)  
{  
	   int size = sizeof(T);  
	   int point_size = sizeof(T*);  
	   //先申請內存,其中point_size * row表示存放row個行指針  
	   T **arr = (T **) malloc(point_size * row + size * row * col);  
	   if (arr != NULL)  
	   {     
		   memset(arr, 0, point_size * row + size * row * col);  
		   T *head = (T*)((BYTECOLORRGB*)arr + point_size * row);  
		   while (row--)  
			            arr[row] = (T*)((BYTECOLORRGB*)head + row * col * size);  
	   }  
	   return (T**)arr;  
}  


//釋放二維數組  
void free_Aarray2D(void **arr)  
{  
	if (arr != NULL)  
		free(arr);
	arr =NULL;
}  


int main()  
{  
	printf("請輸入行列(以空格分開): ");  
	int nRow, nCol;  
    scanf("%d %d", &nRow, &nCol);  
    //動態申請連續的二維數組  
	BYTECOLORRGB **p = malloc_Array2D<BYTECOLORRGB>(nRow, nCol);  
	//爲二維數組賦值     
	p[0][0].red = 20;
	printf("%4d ", p[0][0].red);
    free_Aarray2D((void**)p);  
    return 0;  
}  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章