In c language Dynamic one-dimensional array is realized by malloc dynamic allocation space, and dynamic two-dimensional array can be realized by malloc dynamic allocation space.
In fact, the C language does not have a two-dimensional array, at least not directly support the two-dimensional array, instead of "array of arrays", two-dimensional arrays can be seen as a pointer to the array of the array. For a two-dimensional array p[i][j], the compiler uses the formula * (* (p+i) +j) to find the value of the group element:
1, p+i calculation line pointer.
2, * (P+i) Specific line, is a pointer to the beginning of the element address.
3, * (p+i) +j get the address of the specific element.
4, * (* (p+i) +j) to get the value of the element.
Based on the above principle, we can allocate a two-dimensional array dynamically by allocating an array of pointers and allocating space for each element of the pointer array.
Realize
The following is a dynamic allocation of two-dimensional arrays I wrote, applicable to any type of two-dimensional array, can be used directly.
Type definitions and error codes
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
Realize
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));
}
}
Use
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);
}