You are here:

C++/Dynamic Memory allocation

Advertisement


Question
QUESTION: Hi Sir, i have to Dynamically allocate memory for 4 dimensional array like A[i][j][k][l].I want to make a function for this problem.
All i,j,k,l should change their values.Plz. suggest me the programme for this using C  


ANSWER: Dear Puneet:

Your program should look something like this:

char ****A = (char****) malloc ( sizeof (char) * ( 3 ) * ( 3 ) * ( 3 ) * ( 3 ) );

for ( int i = 0 ; i < 3 ; ++ i )
{
 for ( int j = 0 ; i < 3 ; ++ i )
 {
   for ( int k = 0 ; i < 3 ; ++ i )
   {
     for ( int l = 0 ; i < 3 ; ++ i )
     {
       A [ i ][ j ][ k ][ l ] = 0 ;
     }
   }
 }
}

---------- FOLLOW-UP ----------

QUESTION: I have dynamically allocated the Array but it gives an error that the image size crosses the limits so it can not be build.
plz suggest me how i can manage with this problem.

Answer
Dear Puneet:
 I am sorry for giving you the wrong answer to this question.  Try this correction:

char ****A = (char****) malloc ( sizeof (char***) * ( 3 ) );

for ( int i = 0 ; i < 3 ; ++ i )
{
A [ i ] = (char***) malloc ( sizeof (char**) * ( 3 ) );
for ( int j = 0 ; j < 3 ; ++ j )
{
  A [ i ] [ j ] = (char**) malloc ( sizeof (char*) * ( 3 ) );
  for ( int k = 0 ; k < 3 ; ++ k )
  {
    A [ i ] [ j ] [ k ] = (char*) malloc ( sizeof (char) * ( 3 ) );
    for ( int l = 0 ; l < 3 ; ++ l )
    {
      A [ i ][ j ][ k ][ l ] = 0 ;
    }
  }
}
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Titus B. Ledbetter, Jr.

Expertise

C , MFC, Object Oriented, Artificial Intelligence

Experience

I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Education/Credentials
Master's Degree Computer Science from Johns Hopkins

©2016 About.com. All rights reserved.