Two-dimensional and two-dimensional arrays have two-dimensional logic, but the two-dimensional array is continuous, two-dimensional space is not necessarily continuous, we can apply for a continuous two-dimensional space, you can also apply for discontinuous two-dimensional space, the following to introduce two applications and return to a two-dimensional space method:
Apply and return a contiguous two-dimensional space, this is to use a pointer array to manage the continuous two-dimensional space.
1#include <stdio.h>2#include <stdlib.h>3 intMainvoid)4 {5 int(*p) [5]=(int(*) [5])malloc(sizeof(int)*3*5);6 intI=0, j=0;7 for(i=0;i<3; i++)8 for(j=0;j<5; j + +)9 {Tenp[i][j]=i*J; One } A for(i=0;i<3; i++) - for(j=0;j<5; j + +) - { theprintf"%d\t", P[i][j]); - } - return 0; -}
Applying and returning a discontinuous two-dimensional space, the principle is to first use a level two pointer to a space. , all of them are first-level pointers, and then each of these level pointers points to a one-dimensional space, so that the two-level pointer to or manages the two-dimensional space.
1#include <stdio.h>2#include <stdlib.h>3 int**allocmem (int Base,intRowintLine )4 {5 int**p= (int**)calloc(sizeof(int*), row);6 intI=0;7 for(i=0; i<row;i++)8 {9P[i]= (int*)calloc(Line,Base);Ten } One returnp; A } - intMainvoid) - { the int Base=sizeof(int); - introw=3, line=5; - int**p=allocmem (Base, row,line); - intI=0, j=0; + intk=0; - for(i=0; i<row;i++) + for(j=0; j<line;j++) A { atp[i][j]=k++; - } - for(i=0; i<row;i++) - for(j=0; j<line;j++) - { -printf"%d\t", P[i][j]); in } - return 0; to}
Request and return two-dimensional space on heap space