Advertisement
Mr_kindle

dynamicllyallocated2dmatrix.c

Nov 12th, 2022 (edited)
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.83 KB | None | 0 0
  1. /*this program tells us how to dynamically allocate memory for 2d matrix*/
  2. /*memory allocated by calloc has initial value '0'*/
  3.  
  4. #include<stdio.h>
  5. #include<malloc.h>
  6. int main()
  7. {   int n=3,i,j;
  8. int *ptr;
  9.     ptr= calloc(n*n, sizeof(int));
  10.     /*to get input from user*/
  11.     for(i=0;i<n;i++)
  12.               {
  13.                  for(j=0;j<n;j++)
  14.                 {
  15.                  printf("Enter the value %d:  ",i*n +j+1);
  16.                  scanf("%d",&ptr[i*n + j]);
  17.              }
  18.                 // printf("\n");
  19.              }
  20.     /*Now display the dynamically allocated 2d matrix*/
  21.     printf("\nHere is your matrix: \n");
  22.     for(i=0;i<n;i++)
  23.               {
  24.                  for(j=0;j<n;j++)
  25.                  printf("%d ",ptr[i*n + j]);
  26.                  printf("\n");
  27.              }
  28. free(ptr);
  29.  
  30. return 0;
  31. }//main
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement