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

I need previous papers of CSC.......plz help out by posting them.......

1818


Describe the order of precedence with regards to operators in C.

633


What is advantage of pointer in c?

696


How can you draw circles in C?

626


What is self-referential structure in c programming?

661






What is a loop?

557


Explain what are linked list?

627


How can you determine the size of an allocated portion of memory?

746


How are strings stored in c?

596


hi... can anyone help me to make a two-dimensinal arrays in finding the sum of two elements plzzz. thnx a lot...

1447


Write a code to achieve inter processor communication (mutual exclusion implementation pseudo code)?

692


What is keyword in c?

605


What are the types of data types and explain?

674


What are bitwise shift operators in c programming?

648


Can we replace the struct function in tree syntax with a union?

783