Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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
#include

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 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 for(k = 0; 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 for(k = 0; k printf("%4d", matrix[s][k]);

printf("\n");
}

/* empty the inner array */
for(i = 0; 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


This post first appeared on Codemio - Programming And Technology - A Software Developer's, please read the originial post: here

Share the post

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

×

Subscribe to Codemio - Programming And Technology - A Software Developer's

Get updates delivered right to your inbox!

Thank you for your subscription

×