Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating memory to 3D array

Tags:

c

pointers

I know how to allocate memory to 2-D array but if the ptr is defined as int *ptr[][100];

Then how can I allocate memory for ptr ?

like image 565
Suraj Menon Avatar asked Dec 05 '25 18:12

Suraj Menon


2 Answers

Quoting from section 6.2.5 of the C standard:

An array type of unknown size is an incomplete type. It is completed, for an identifier of that type, by specifying the size in a later declaration (with internal or external linkage).

thus, to use int *ptr[][100]; you have to link against a definition of it. If you specify that length then you have a 2D array of pointers to int. At this point you have to allocate a chunk of memory large enough for the 3D array, and assign correctly each int * in the 2D array.

A more straightforward approach could be the following:

int nx = 100;
int ny = 200;
int nz = 300;

int (*parray)[ny][nz] = malloc(nx*ny*nz*sizeof(int));

The last line allocate a pointer to an array of an array of int, that can be effectively used like a 3D array. For instance:

for(int ii = 0; ii < nx; ii++)
  for (int jj = 0; jj < ny; jj++)
    for (int kk = 0; kk < nz; kk++)
      parray[ii][jj][kk] = ii*ny*nz + jj*nz + kk;

The accepted answer to this question gives a really nice and precise overview of the use of pointers to array of types.

like image 124
Massimiliano Avatar answered Dec 07 '25 15:12

Massimiliano


Use malloc and specify the amount of bytes you need for the 3D array.

int *array3d = (int *)malloc(x * y * z * sizeof(int));

where x, y and z are the dimensions of your 3d array.

You can of course also have other types of array elements (float, chars, structs), just make sure you get the correct size using sizeof.

like image 31
DrummerB Avatar answered Dec 07 '25 17:12

DrummerB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!