I have the following class in C++11:
class MyTable
{
public:
enum class EntryType
{
USED, FREE
};
MyTable(EntryType value)
{
for (uint32_t i = 0; i < 10; ++i)
{
memset(_table[i].data(), (int)value, sizeof(_table[0][0]) * 50);
}
}
array<array<EntryType, 50>, 10> _table;
}
Trying to construct an object of MyTable with value of EntryType::FREE, every item in the 2-dimensional array has the value of 0x01010101 (1b every 8 bits), instead of the expected value of just 0x1
I'm guessing it has something to do with my value
being casted to int
, but I don't know what I'm supposed to do in order to fix it.
Initialization of two-dimensional array A better way to initialize this array with the same array elements is given below: int test[2][3] = { {2, 4, 5}, {9, 0, 19}}; This array has 2 rows and 3 columns, which is why we have two rows of elements with 3 elements each.
Two – Dimensional Arrays Like the one dimensional array, 2D arrays can be initialized in both the two ways; the compile time initialization and the run time initialization. int table-[2][3] = { { 0, 2, 5} { 1, 3, 0} };
No, it cannot.
memset()
is expected to work that way, since it's
sets each byte of the destination buffer to the specified value.
Read more in Why is memset() incorrectly initializing int?
However, be careful, since as juanchopanza said, std::array
may have padding at the end (read more in std::array alignment
), which means that this approach might fail.
Since it's a 2D array, you could use a range-based-for loop and std::array::fill
, like this:
for(auto& row : _table)
row.fill(value);
as renzo stated.
In case you do not want to set every row at the same value, you could do it like this of course:
for(auto &row : array)
for(auto &col : row)
col = value;
Read more in range-based for on multi-dimensional array.
This can be done with a ranged-based for loop and the std::array::fill
member function.
MyTable(EntryType value)
{
for (auto& row : _table) {
row.fill(value);
}
}
This will continue to work even if you change the array dimensions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With