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

What does double pointer mean in c?

805


How can you draw circles in C?

871


Differentiate call by value and call by reference?

768


What is the difference between array and pointer?

797


Explain how can I right-justify a string?

830


What is difference between structure and union in c?

762


Can we compile a program without main() function?

892


What are the advantages of c language?

865


For what purpose null pointer used?

833


difference between native and cross compilers

1893


How can I make sure that my program is the only one accessing a file?

977


What is difference between array and pointer in c?

782


why return type of main is not necessary in linux

1900


Tell me is null always defined as 0(zero)?

862


the statement while(i) puts the entire logic in loop. this loop is called a) indefinite loop b) definite loop c) loop syntax wrong d) none of the above

824