【发布时间】:2021-10-30 01:10:43
【问题描述】:
我在 C++ 中有一个矩阵,定义为 std::array 的 std::array,我想将其统一设置为给定值。对于 C 样式数组(int a[10][10] 等...),我找不到像 C 样式 memset 这样简单的东西。
我使用 std::memset 尝试了一些东西,但没有奏效(数组中有奇怪的东西)。
#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);
在输出中我得到了:
Initial Matrix:
11 12 13
21 22 23
31 32 33
Matrix reset:
1028 1028 1028
1028 1028 1028
1028 1028 1028
我不知道我的代码出了什么问题,以及我应该怎么做才能重置我的矩阵。
帮助您帮助我的其他调试信息:
- 如果我使用 value = 0 进行 memset,我的代码将打印一个充满 0 的矩阵(酷 =))
- 如果我的 memset 值 = 1,我的代码会打印一个充满 257 的矩阵
- 如果 memset 的值 = 2,我的代码会打印一个充满 514 的矩阵
- 如果 memset 的值 = 3,我的代码会打印一个充满 771 的矩阵
我可以看到2的幂,可能与我使用std ints(uint16_t)有关,我的大脑现在已经死了,我想不通。
【问题讨论】:
-
您的 memset 显示 UB,因为矩阵的类型为
std::array,但您正尝试以std::uint16_t的形式访问其中的一部分。 -
@bitmask 你能详细说明一下吗?我不确定我是否理解这一点
-
基本上
matrix不是std::uint16_t类型的对象。因此,您无法访问它(无论是读取还是写入)。从语言的角度来看,编译器如何在内存中布置数据是无关紧要的。
标签: c++ std memset stdarray uint16