0
int ***darray;  (darray[x][y][z] )

I want to allocate the memory for the last dimension in a while loop., i.e. z is incremented for each iteration of the loop. The number of iterations are unknown apriori.

i have allocated memory for the first 2 dimensions as below

darray = calloc (x, sizeof(int**));

for ( i=0; i< x; i++)
   darray[i] = calloc (y, sizeof(int*) );

I'm having trouble allocating darray[i][j][k] element i want to perform

`for ( i= 0; i< x; i++)
{
   for ( j=0; j< y; j++)
   {
       Break= TRUE;
       k=0;
       while ( Break )
       {
         darray[i][j][k] = VarX;

         if ( VarX > 10 )
               Break = FALSE;
         k++;

       }
    }
}

`

  • [May help](http://stackoverflow.com/questions/2306172/malloc-a-3-dimensional-array-in-c) – Dayal rai Apr 24 '15 at 09:24
  • @Dayalrai For the record, I never downvoted your now deleted answer. (I commented so you could consider improving it.) – Iskar Jarak Apr 24 '15 at 09:25
  • @IskarJarak thanks. I will keep it in mind in all my future post :) – Dayal rai Apr 24 '15 at 09:26
  • Allocation can fail - don't forget to check the return value of `malloc`/`realloc`/`calloc` calls! – Iskar Jarak Apr 24 '15 at 09:29
  • 2
    You aren't even allocating a 3D array, you are allocating a fragmented lookup table. Instead of exploding your data all over the heap, allocate it as a real array in adjacent memory. – Lundin Apr 24 '15 at 09:31

1 Answers1

2

You already created 2 dimensions. Now just allocate the third:

for( size_t i = 0 ; i < x ; i++ )
{
    for( size_t j = 0 ; j < y ; j++ )
    {
        darray[i][j] = calloc( z , sizeof( int ) ) ;
    }
}
2501
  • 25,460
  • 4
  • 47
  • 87