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

Explain how can you restore a redirected standard stream?

786


What is the use of the function in c?

796


Write a program to find factorial of a number using recursive function.

859


write a program to concatenation the string using switch case?

1807


What is extern variable in c with example?

767


How will you declare an array of three function pointers where each function receives two ints and returns a float?

1075


List a few unconditional control statement in c.

773


What does the characters “r” and “w” mean when writing programs that will make use of files?

1187


What happens if you free a pointer twice?

818


If a variable is a pointer to a structure, then which operator is used to access data members of the structure through the pointer variable?

1017


Is it possible to initialize a variable at the time it was declared?

1006


What is a node in c?

737


Explain how are 16- and 32-bit numbers stored?

1021


`write a program to display the recomended action depends on a color of trafic light using nested if statments

1892


if (i = 0)printf ("True"); elseprintf("False"); Under what conditions will the above print out the string "True" a) Never b) Always c) When the value of i is 0 d) all of the above

926