C Code Snippets 11 - Dynamic Memory Allocation: calloc()



Hello everyone, today's C code snippet will be on dynamic multidimensional arrays. First, I allocate the required space by using calloc() function for the matrix according to the entered row and column values. Then I ask the user to enter these elements one by one. Finally the matrix is printed.



The calloc function is used to allocate storage to a variable while the program is running. This library function is invoked by writing calloc(num,size). The important difference between malloc and calloc function is that calloc initializes all bytes in the allocation block to zero and the allocated memory may/may not be contiguous.

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
Author:

Software Developer, Codemio Admin

Disqus Comments Loading..