I have a matrix in C++ defined as a std::array
of std::array
that I would like to set uniformly to a given value. I can't find something as simple as C-style memset for C-Style array (int a[10][10] etc...).
I tried something using std::memset but did not worked (got weird stuff in the array).
#include <stdint.h> // uint16_t
#include <cstring> // using std::memset ?
#include <iostream> // to print values
// To display the values
template <typename T, std::size_t SIZE>
void Display2D(const std::array< std::array<T, SIZE>, SIZE> &matrix)
{
for (int l = 0; l < matrix.size(); l++)
{
for (int c = 0; c < matrix[l].size(); c++)
{
std::cout << (int)matrix[l][c] << " ";
}
std::cout << std::endl;
}
}
// Initialize the matrix with some values
constexpr uint8_t n = 3;
std::array<uint16_t, n> l1{11, 12, 13};
std::array<uint16_t, n> l2{21, 22, 23};
std::array<uint16_t, n> l3{31, 32, 33};
std::array< std::array<uint16_t, n>, n> matrix{l1, l2, l3};
std::cout << "Initial Matrix:" << std::endl;
Display2D(matrix);
// Try to reset it uniformly to a given value
std::memset(&matrix, (uint16_t) 4, n * sizeof(matrix[0]));
std::cout << "Matrix reset:" << std::endl;
Display2D(matrix);
In output I got :
Initial Matrix:
11 12 13
21 22 23
31 32 33
Matrix reset:
1028 1028 1028
1028 1028 1028
1028 1028 1028
I can't figure out what's wrong in my code, and what I should do to reset my matrix.
Additional debug info to help you helping me:
- if I memset with value = 0, my code prints a matrix full of 0 (cool =) )
- if I memset with value = 1, my code prints a matrix full of 257
- if I memset with value = 2, my code prints a matrix full of 514
- if I memset with value = 3, my code prints a matrix full of 771
I can see the power of 2 in this, probably related to the fact that I uses std ints (uint16_t), by my brain is dead right now, I can't figure it out.