一:C中动态分配二维数组(1)内存不连续的分配
- #include <stdio.h>
- #include <malloc.h>
- #define M 3
- #define N 3
- // 这样在同一个数组内是连续分配的,但是实际上是不连续分配的
- int main(int argc , char*argv[])
- {
- int i ,j ;
- int **matric ;
- matric = (int**)malloc(M*sizeof(int*));
- for(i = 0 ; i<M ; i++)
- *(matric+i) = (int*)malloc(N*sizeof(int));
- for(i = 0 ; i<M ; i++)
- for(j=0 ; j<N ; j++)
- {
- printf("Please entry the %d value:
",i*N+j);
- scanf("%d",(*(matric+i)+j));
- }
- for(i = 0 ; i<M ; i++)
- {
- switch(i)
- {
- case 0 :
- printf("第一行数组元素:
");
- break ;
- case 1:
- printf("第二行数组元素:
") ;
- break ;
- case 2:
- printf("第三行数组元素:
") ;
- break;
- }
- for(j = 0 ; j<N ; j++)
- {
- printf("The values of %d elements are:%d
",i*N+j,*(*(matric+i)+j));
- printf("The pointer position is:%x
",(*(matric+i)+j)) ;
- }
- }
- for(i = 0 ;i<M ; i++)
- {
- free(*(matric+i));
- }
- free(matric) ;
- return 0 ;
- }
运行结果为:可以明确看出内存是不连续的。