Advertisement
kaenan

C - Matrix

Dec 2nd, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. /*
  2.  * TODO: Generinc I/O
  3.  */
  4.  
  5.  
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8.  
  9. #define SUCCESS 0
  10. #define NEWLINE puts("")
  11.  
  12. /* Error checked malloc and realloc. */
  13. void *ec_malloc(size_t size);
  14. void *ec_realloc(void *ptr, size_t size);
  15.  
  16. #define mm(size, type) (type *) ec_malloc(size * sizeof(type))
  17.  
  18. /* Allocate a matrix of any type. */
  19. #define mem_matrix(matrix, rows, cols, type) ;\
  20.     matrix = mm(rows, type*);\
  21.     for (int i = 0; i < rows; ++i) {\
  22.         matrix[i] = mm(cols, type);\
  23.     }
  24.  
  25. /* Deallocate a matrix of any type. */
  26. #define free_matrix(matrix, rows) ;\
  27.     for (int i = 0; i < rows; ++i) {\
  28.         free(matrix[i]);\
  29.     }\
  30.     free(matrix);
  31.  
  32. /* Read and print a matrix. */
  33. void readmat(int **, unsigned int, unsigned int);
  34. void printmat(int **, unsigned int, unsigned int);
  35.  
  36.  
  37. void printmat(int **mat, unsigned int rows, unsigned int cols)
  38. {
  39.     NEWLINE;
  40.  
  41.     for (
  42.         unsigned int ln_index = 0;
  43.         ln_index < rows;
  44.         ++ln_index
  45.         )
  46.     {
  47.         for (
  48.             unsigned int col_index = 0;
  49.             col_index < cols;
  50.             ++col_index
  51.             )
  52.         {
  53.             printf("%d ",mat[ln_index][col_index]);
  54.         }
  55.         NEWLINE;
  56.     }
  57.  
  58.     NEWLINE;
  59. }
  60.  
  61.  
  62.  
  63. void readmat(int **mat, unsigned int rows, unsigned int cols)
  64. {
  65.     for (
  66.         unsigned int ln_index = 0;
  67.         ln_index < rows;
  68.         ++ln_index
  69.         )
  70.     {
  71.         for (
  72.             unsigned int col_index = 0;
  73.             col_index < cols;
  74.             ++col_index
  75.             )
  76.         {
  77.             scanf("%d", mat[ln_index] + col_index);
  78.         }
  79.     }
  80. }
  81.  
  82.  
  83.  
  84.  
  85. void *ec_realloc(void *ptr, size_t size)
  86. {
  87.     void *new_ptr;
  88.  
  89.     new_ptr = realloc(ptr, size);
  90.  
  91.     if (!new_ptr) {
  92.         perror("[Error] realloc() returned NULL\n");
  93.         exit(-1);
  94.     }
  95.  
  96.     return new_ptr;
  97. }
  98.  
  99. void *ec_malloc(size_t size)
  100. {
  101.     return ec_realloc(NULL, size);
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement