fgallego

C++ Matrix Allocation, Printing, Deallocation example

Nov 27th, 2017 (edited)
472
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | Source Code | 0 0
  1. #include <cstdint>
  2. #include <iostream>
  3.  
  4. constexpr uint32_t M_ROWS = 5, M_COLS = 5;
  5.  
  6. uint32_t** reserve_matrix(uint32_t const rows, uint32_t const cols) {
  7.     uint32_t** m = new uint32_t*[rows];
  8.     for (std::size_t i{0}; i < rows; ++i) {
  9.         m[i] = new uint32_t[cols];
  10.     }
  11.  
  12.     return m;
  13. }
  14.  
  15. void free_matrix(uint32_t** m, uint32_t const rows) {
  16.     for(std::size_t i{0}; i < rows; ++i) {
  17.         delete[] m[i];
  18.     }
  19.     delete[] m;
  20. }
  21.  
  22. void populate_matrix(uint32_t** m, uint32_t const rows, uint32_t const cols) {
  23.     for(std::size_t j{0}; j < rows; ++j) {
  24.         for(std::size_t i{0}; i < cols; ++i) {
  25.             m[j][i] = j+i;
  26.         }
  27.     }
  28. }
  29.  
  30. void print_matrix(uint32_t** m, uint32_t const rows, uint32_t const cols) {
  31.     for(std::size_t j{0}; j < rows; ++j) {
  32.         for(std::size_t i{0}; i < cols; ++i) {
  33.             std::cout << m[j][i] << " ";
  34.         }
  35.         std::cout <<"\n";
  36.     }
  37. }
  38.  
  39. int main() {
  40.     uint32_t** m = reserve_matrix(M_ROWS, M_COLS);
  41.     populate_matrix(m, M_ROWS, M_COLS);
  42.     print_matrix(m, M_ROWS, M_COLS);
  43.     free_matrix(m, M_ROWS);
  44. }
Add Comment
Please, Sign In to add comment