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 is difference between structure and union with example?

605


What does sizeof function do?

627


How macro execution is faster than function ?

677


Write a program in c to replace any vowel in a string with z?

703


Explain setjmp()?

663






Explain 'bus error'?

572


Write a code to remove duplicates in a string.

639


Does c have an equivalent to pascals with statement?

580


Hi how many types of software editions are there and their difference (like home editions, enterprise, standard etc) can u please help me

1474


ATM machine and railway reservation class/object diagram

4813


Can a function argument have default value?

680


What is the difference between a function and a method in c?

573


Can the sizeof operator be used to tell the size of an array passed to a function?

626


What is volatile variable how do you declare it?

574


which of the following is allowed in a "C" arithematic instruction a) [] b) {} c) () d) none of the above

1145