试着直接malloc一个2*3*4的空间来模拟数组:
#include <stdio.h> #include <malloc.h> int main(void) { int*** pArr = NULL; pArr = (int ***)malloc(2*3*4*sizeof(int)); if(pArr == 0) { return -1; } memset(pArr, 0, 2*3*4*sizeof(int)); pArr[0][0][1] = 11; printf("pArr[0][0][1] = %d\n" , pArr[0][0][1]); free(pArr); pArr = NULL; return 0; } /* [email protected]:/work/dcc# gcc 1.c ;./a.out 1.c: In function ‘main’: 1.c:17: warning: incompatible implicit declaration of built-in function ‘memset’ Segmentation fault */
创建与释放一个三维数组:
#include <stdio.h> #include <malloc.h> int*** Malloc3DActiveArray(int*** pArr, int x, int y, int z); void Free3DActiveArray(int*** pArr, int x, int y); //void Display3DArray(int*** pArr, int x, int y, int z); int main(void) { int x, y, z; int*** array = NULL; printf("输入一维长度: "); scanf("%d",&x); printf("输入二维长度: "); scanf("%d",&y); printf("输入三维长度: "); scanf("%d",&z); array = Malloc3DActiveArray(array, x, y, z); printf("1\n"); printf("array[0][0][1] = %d\n", array[0][0][1]); Free3DActiveArray(array, x, y); array = NULL; return 0; } int*** Malloc3DActiveArray(int *** pArr, int x, int y, int z) { int i, j, k; pArr = (int ***)malloc(x * sizeof(int **)); //第一维 for (i = 0; i < x; i++) { pArr[i] = (int **)malloc(y * sizeof(int *));//第二维 for (j = 0; j < y; j++) { pArr[i][j] = (int *)malloc(z * sizeof(int));//第三维 for (k = 0; k < z; k++) { pArr[i][j][k] = i + j + k + 1; printf("%d ", pArr[i][j][k]); } printf("\n"); } printf("\n"); } return pArr; } void Free3DActiveArray(int*** pArr, int x, int y) { int i, j; for (i = 0; i < x; i++) { for (j = 0; j < y; j++) { free(pArr[i][j]);//第三维 pArr[i][j] = 0; } free(pArr[i]);//第二维 pArr[i] = 0; } free(pArr);//第一维 } /* [email protected]:/work/dcc# gcc 1.c ;./a.out 输入一维长度: 1 输入二维长度: 2 输入三维长度: 3 1 2 3 2 3 4 1 array[0][0][1] = 2 */
时间: 2024-11-03 21:18:25