Advertisement
2607

d11q1

Sep 16th, 2021
1,375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void dynamic_array_print(int **A, size_t N, size_t M)
  5. {
  6.     for(int i = 0; i < N; i++) {
  7.         for(int j = 0; j < M; j++) {
  8.             printf("%*d", 5, A[i][j]);
  9.         }
  10.         printf("\n");
  11.     }
  12. }
  13.  
  14. /*
  15.     return pointer on 2d dynamic array
  16.     !allocates memory -> to be freed later
  17. */
  18. int ** dynamic_array_alloc(size_t N, size_t M)
  19. {
  20.     int **A = (int **)malloc(N*sizeof(int *));
  21.     for(int i = 0; i < N; i++) {
  22.         A[i] = (int *)malloc(M*sizeof(int));
  23.     }
  24.     return A;
  25. }
  26.  
  27. void dynamic_array_free(int **A, size_t N)
  28. {
  29.     for(int i = 0; i < N; i++) {
  30.         free(A[i]);
  31.     }
  32.     free(A);
  33. }
  34.  
  35. void dynamic_array_test(size_t N, size_t M)
  36. {
  37.     int **A = dynamic_array_alloc(N, M);
  38.     int x = 1;
  39.     for(int i = 0; i < N; i++) {
  40.         for(int j = 0; j < M; j++) {
  41.             A[i][j] = x;
  42.             x += 1;
  43.         }
  44.     }
  45.     dynamic_array_print(A, N, M);
  46.     /*memory investigation*/
  47.     printf("\n Pointers to lines: ");
  48.     for(int **p = A; p < A + 3; p++)
  49.         printf("%10d", (long int)*p);
  50.     printf("\n Direct memory access:\n");
  51.     for(int *p = (int*)*A; p < (int*)*A + 15; p++)
  52.         printf("%d\t", *p);
  53.     dynamic_array_free(A, N);
  54. }
  55.  
  56. int main()
  57. {
  58.     int matrix_height = 4;
  59.     int matrix_width = 5;
  60.  
  61.     dynamic_array_test(matrix_height, matrix_width);
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement