calloc function is used to reserve space for dynamic arrays and it has the following form;
void * calloc (size_t n, size_t size);
Number of elements in the first argument specifies the size in bytes of one element to the second argument. A successful partitioning, that address is returned, NULL is returned on failure therefore we check this condition by using an if-else statement.
The following code shows the use of calloc function with dynamic multidimensional arrays.
/**
* Author : Berk Soysal
*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int **matrix;
int rows, columns;
int s, k;
int i;
printf("How many rows: ");
scanf("%d", &rows);
printf("How many columns: ");
scanf("%d", &columns);
// allocate space for the outer array
matrix = (int **) calloc(rows, sizeof(int));
// allocate space for the inner array
for(i = 0; i < rows; i++)
matrix[i] = (int *) calloc(columns, sizeof(int));
if(matrix == NULL){
printf("Cannot allocate memory space!");
exit(1);
}
//read the elements of the matrix
for(s = 0; s < rows; s++)
for(k = 0; k < columns; k++) {
printf("Enter the element of the matrix: Matrix[%d][%d] = ", s, k);
scanf("%d", &(matrix[s][k]));
}
printf("\nThis is the matrix you have entered:\n");
for(s = 0; s < rows; s++) {
for(k = 0; k < columns; k++)
printf("%4d", matrix[s][k]);
printf("\n");
}
/* empty the inner array */
for(i = 0; i < rows; i++)
free((void *) matrix[i]);
/* empty the outer array */
free((void *) matrix);
return(0);
}
Output:
Please leave a comment if you have any questions or comments..
Keywords: CCode Snippets
Disqus Comments Loading..