How can I set an array's size at run time?

Answer Posted / rajendra

#include <stdlib.h> /* EXIT_FAILURE, EXIT_SUCCESS */
#include <errno.h>
#include <stdio.h>

#define ROW 5
#define COL 5

int
main ( void )
{
int **cont_arr;
int **cont_arr;

int **arr = malloc ( ROW * sizeof ( int * ) );
if ( !arr )
{
perror ( "Error" );
exit ( EXIT_FAILURE );
}

for ( i=0; i < ROW; i++ )
{
arr[i] = malloc ( sizeof ( int ) * COL );
if ( !arr[i] )
{
perror ( "Error" );
exit ( EXIT_FAILURE );
}
}

/*
* Contiguous memory allocated for array.
Below.
*/

cont_arr = (int **) malloc ( ROW * sizeof ( int
* ) );
if ( !cont_arr )
{
perror ( "Error" );
exit ( EXIT_FAILURE );
}

cont_arr[0] = (int *) malloc ( ROW * COL *
sizeof ( int ) );
if ( !cont_arr[0] )
{
perror ( "Error" );
exit ( EXIT_FAILURE );
}

for ( int i=1; i < ROW; i++ )
cont_arr[i] = cont_arr[0] + i * COL;

exit ( EXIT_SUCCESS );
}

Is This Answer Correct ?    4 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Do character constants represent numerical values?

833


Can we declare variable anywhere in c?

532


what type of questions arrive in interview over c programming?

1545


What is the easiest sorting method to use?

628


can any one tel me wt is the question pattern for NIC exam

1551






What are keywords in c with examples?

596


What is a void pointer? When is a void pointer used?

614


Can you assign a different address to an array tag?

691


in case any function return float value we must declare a) the function must be declared as 'float' in main() as well b) the function automatically returned float values c) function before declared 'float' keyword d) all the above

586


What is header file in c?

597


What is c preprocessor mean?

775


Why do we use stdio h and conio h?

625


to find the closest pair

1813


How will you divide two numbers in a MACRO?

695


What is scanf () in c?

655