In this article we are going to demonstrate a program that reads the data in the form using pointers and we allocate the memory dynamically for the pointer operations to run.
We will get a brief understanding about the system memory and it’s instances.
What is Dynamic memory allocation ??
C dynamic memory allocation refers to performing manual memorymanagement for dynamic memory allocation in the C programming language via a group of functions in the C standard library, namely malloc, realloc, calloc and free.
In the below program we are going to establish a dynamic array to store the data.
We use the memory allocation functions for the allocation of the data into the individual index of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #include "stdio.h" int main() { int m, n; printf("Enter no. of rows and columns: "); scanf("%d%d", &m, &n); int **a; //Allocate memory to matrix a = (int **) malloc(m * sizeof(int *)); for(int i=0; i<m; i++) { a[i] = (int *) malloc(n * sizeof(int)); } //Read elements into matrix printf("Enter matrix elements: "); for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { scanf("%d", &a[i][j]); } } //Print elements in the matrix printf("Matrix elements are: \n"); for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { printf("%d ", a[i][j]); } printf("\n"); } //Dellocating memory of matrix for(int i=0; i<m; i++) { free(a[i]); } free(a); return 0; } |
Input and output for the above program is as follows:
1 2 3 4 5 6 7 8 9 10 11 | Enter no. of rows and columns: 3 3 Enter matrix elements: 1 2 3 4 5 6 7 8 9 Matrix elements are: 1 2 3 4 5 6 7 8 9 |