Reduce the no of calls to malloc, to allocate a 2-d array.
int** allocate_matrix(int cols, int rows)
{
int i;
int ** matrix;
matrix = ( int**) malloc (rows*sizeof(int *));
if(matrix == NULL){
printf("Memory allocation failed while allocating for matrix[].\n");
exit(-1);
}
for(i = 0; i < rows; ++i){
matrix[i] = (int *) malloc(cols * sizeof(int));
if(matrix[i] == NULL){
printf("Memory allocation failed while allocating for matrix[i][].\n");
exit(-1);
}
}
return matrix;
}
int** allocate_matrix(int cols, int rows)
{
int i;
int ** matrix;
matrix = ( int**) malloc (rows*sizeof(int *));
if(matrix == NULL){
printf("Memory allocation failed while allocating for matrix[].\n");
exit(-1);
}
for(i = 0; i < rows; ++i){
matrix[i] = (int *) malloc(cols * sizeof(int));
if(matrix[i] == NULL){
printf("Memory allocation failed while allocating for matrix[i][].\n");
exit(-1);
}
}
return matrix;
}
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks