Try to directly malloc a 2*3*4 space to emulate the array:
#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] = one; 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 ' segmentatio N fault*/
Create and release a three-dimensional array:
#include <stdio.h> #include <malloc.h>int*** malloc3dactivearray (int*** pArr, int x, int y, int z); void Free3d Activearray (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 ("Input one-dimensional length:"); scanf ("%d", &x); printf ("Input two-dimensional length:"); scanf ("%d", &y); printf ("Input three-dimensional length:"); 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 * *)); The first dimension for (i = 0; i < x; i++) {parr[i] = (int * *) malloc (y * sizeof (int *));//second dimension for (j = 0; J < ; Y J + +) {Parr[i][j] = (int *) malloc (z * sizeof (int));//Third dimension 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]);//third-dimensional PA RR[I][J] = 0; } free (parr[i]);//second dimension parr[i] = 0; } free (PARR);//First dimension}/*[email protected]:/work/dcc# gcc 1.c;. /a.out input one-dimensional length: 1 input two-dimensional length: 2 input three-dimensional length: 2 3 2 3 4 1array[0][0][1] = 2*/
Dynamic allocation and release of memory in C language (multidimensional dynamic array construction)
C language, dynamic array