Monday, 15 March 2010

c - dynamic allocation/deallocation of 2D & 3D arrays -


I know about algorithms that have to be dynamically allocated / deployed 2D array, although I have 3d arrays I am not sure about the same.
Using this knowledge and a bit of symmetry, I came up with the following code.
(During coding I found a difficult time in 3D).

Please comment on the right and suggest any better option (skill wise or subtle), if any. Apart from this, I think these two 2D and 3D arrays normally have static arrays such as arr2D [2] [3] and
AR 3D [2] [3] [2] correct?

Code for 2D

  // A 2D array int ** assigns 2D (int rows, int cols) {int ** arr2D; Int i; Arr2D = (int **) malloc (rows * size (int *)); {Arr2D [i] = (int *) malloc for (I = 0; i & lt; rows; i ++) * Column * size (int)); }} // Delete a 2D array from zero 2D (at ** AR2D, int lines) {int i; For (i = 0; i  

code for 3D

  // assign a 3D array int *** allocated (int, int m, int N) {int ** * arr3D; Int i, j, k; Arr3D = (int ***) malloc (L * size (int **)); {Arr3D [i] = (int **) malloc (m * sizeof (int *)) for (i = 0; i & lt; l; i ++); For (j = 0; j & lt; m; j ++) {arr3D [i] [j] = (integer *) malloc (n * sizeof (int)); }} Return arr3D; } // Assign a 3D array zero deallocate3D (int arr3D, int l, int m) {int i, j; For (i = 0; i & lt; l; i ++) {for (int j = 0; j & lt; m; j ++) {free (arr3d [i] [j]); } Free (AR3D [ii]); } Free (arr3D); } You can also assign an array and calculate individual indices.  

You can also assign an array and calculate individual indices. This requires less allocated calls and results in less fragmentation and better cache usage.

  typedef struct {int a; Int b; Int * data; } Int2d; Int2d arr2d = {2, 3}; Arr2d.data = malloc (arr2d.a * arr2d.b * sizeof * arr2d.data);  

now becomes arr2d [r] [c] arr2d.data [r * arr2d.b + c] . Deallocation is an independent () distance. As a bonus you will always keep your dynamic array size with you.

Extrapoling for 3D:

  Type-e structure {int a; Int b; Int c; Int * data; } Int3d; Int 3D AR3 = {2, 3, 4}; Arr3d.data = malloc (arr3d.a * arr3d.b * arr3d.c * sizeof * arr3d.data); // arr3d [r] [c] [d] gets //: arr3d.data [r * (arr3d.b * arr3d.c) + c * arr3d.c + d];  

You should allocate allocation operations for these index operations (and for that (D-)) in a different function or macro.

(The names of r, c, And D could be better & mdash; I was going to row, column, and depth. While A, B, and C are the boundaries of their respective dimensions, you can choose something like N1, N2, N3 Or even use an array for them.)


No comments:

Post a Comment