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;  
}  


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