Searching for "dynamically"

Q:

Can I increase the size of a dynamically allocated array? < Yes / No> if yes, how?

Answer

Yes, using the realloc() function as shown below:


main()


{


        int *p;


        p = ( int *) malloc (20) ;


        t = p;


        t = (int *) realloc ( p, 40);


        if ( t == NULL )


        Printf (" Cannot reallocate, leaves previous allocated region unchanged ");


       else


       {


              if ( p ==t )


              ;  / * the array expanded at the same region */


             else


            { 


                 free ( p ); / * deallocate the original array */


                 p = t;  /* set p to newly allocated region */


             }


      }


}  

Report Error

View answer Workspace Report Error Discuss

Subject: Programming

Q:

How would you dynamically allocate a 2-D array of integers?

Answer

#include "alloc.h"


#define MAXROW 3


#define MAXcol 4


main()


{


        int *p, i, J;


        p = (int *) malloc (MAXROW * MAXCOL * sizeof (int));


         for ( i=0; i < MaxROW ; i++)


         {


                for (j=0; j < MAXCOL ; j++)


                { 


                      p [ i * MAXCOL + j] = i;


                       printf ( "%d", p [i * MAXCOL + j] );


                 }


                  printf ("\n");


          }


}

Report Error

View answer Workspace Report Error Discuss

Subject: Programming