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++;

       }
    }
}

`

5
  • May help Commented Apr 24, 2015 at 9:24
  • @Dayalrai For the record, I never downvoted your now deleted answer. (I commented so you could consider improving it.) Commented Apr 24, 2015 at 9:25
  • @IskarJarak thanks. I will keep it in mind in all my future post :) Commented Apr 24, 2015 at 9:26
  • Allocation can fail - don't forget to check the return value of malloc/realloc/calloc calls! Commented Apr 24, 2015 at 9: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. Commented Apr 24, 2015 at 9:31

1 Answer 1

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 ) ) ;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Good to see the use of size_t. Would be nice if you'd round out your answer to show all three allocation steps though.
The size of z is not known. it is incremented in a loop

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.