辛勤的鸟儿总能找到虫子....
分类: C/C++
2008-11-09 21:20:52
typedef unsigned char MK_Byte; #define SUCCESS 0 /*No error*/ #define MFAILED 1 /*General failure*/ #define MNOMEMORY 2 /*Out of memory*/ 声明 //确保初始化 #define DeclareTwoDArray(ATYPE, iname) ATYPE ** iname = NULL //定义自己的malloc和free,确保内存正确操作 #define MKMALLOC(nsize) malloc(nsize) #define MKFREE(name) \ if (NULL != name)\ free(name);\ name = NULL |
int MKCreatArray(int nsize, int X, int Y, void *** parray) { void ** tdarray = NULL; MK_Byte * tmparray = NULL; int i = 0; *parray = NULL; //分配指针数组 if (!(tdarray = (void **)MKMALLOC(sizeof(MK_Byte *) * Y))) { return MNOMEMORY; } //分配实际数组空间 if (!(tmparray = (MK_Byte * )MKMALLOC(nsize * (X * Y)))) { MKFREE(tdarray); return MNOMEMORY; } //初始化内存 memset(tmparray, 0x00, nsize * (X * Y)); //指针数组赋值 for (i = 0; i < Y; i ) tdarray[i] = (tmparray (i * X) * nsize); *parray = tdarray; return SUCCESS; } void MKFreeArray(void *** parray) { if (*parray) { MKFREE((*parray)[0]); MKFREE((*parray)); } } |
void testTwoDArray() { //声明数组 DeclareTwoDArray(int, a); DeclareTwoDArray(float,b); //创建整型数组 MKCreatArray(sizeof(int), 3, 2, &a); a[1][2] = 10; a[0][1] = 23; printf("%d,%d\n",a[1][2],a[0][1]); //使用完一定要FREE MKFreeArray(&a); //重新分配数组 MKCreatArray(sizeof(int), 6, 6, &a); a[5][5] = 234; a[4][0] = 567; printf("%d,%d\n",a[5][5],a[4][0]); MKFreeArray(&a); //创建浮点数组 MKCreatArray(sizeof(float),2,2,&b); b[0][0] = 0.5f; b[1][1] = 0.006f; printf("%g,%g\n",b[0][0],b[1][1]); MKFreeArray(&b); } |