代码:
unsigned char data[20][20] =
{{50, 50....},
....
....};
Mat speed(20, 20, data);
当我尝试访问 speed.data
中的内容时,它说:
在 speed tracking.exe 中的 0x003D2094 抛出异常:0xC0000005:访问冲突读取位置 0x32323233。
例如,std::cout << img.data[0][1];
.
在另一个文件中 mat.h
, Mat
的定义是:
// two-dimensional matrix, type of data is unsigned char
class Mat {
public:
Mat(size_t rows_, size_t cols_, void* data_ = nullptr)
: rows(rows_), cols(cols_), data((unsigned char**)data_) {}
Mat() : rows(0), cols(0), data(nullptr) {}
bool empty() const; // return true if data == nullptr
size_t rows, cols; // the size of the matrix
unsigned char** data; // the contents of the matrix
};
那么为什么我不能访问speed.data
中的内容呢? ?
最佳答案
事实上,您在分配 Mat::data = data
时进行了错误的转换,因为左侧的类型为 unsigned char**
而右侧的类型为unsigned char (*)[20]
的类型。
假设在这种容易出错的转换之后,您尝试通过 Mat::data
访问一些数组元素,例如评估 Mat::data[0][1]
(这当然是个坏主意)。
回想一下 Mat::data[0][1] = *(*(Mat::data + 0) + 1)
。
Mat::data + 0
的类型为 unsigned char**
,其值等于 data
数组的地址.
然后 *(Mat::data + 0)
具有 unsigned char*
的类型和我们现在要计算的值。
正如我从发布的崩溃报告中看到的那样,在您的机器上地址是 4 字节长。所以 data
数组的前 4 个元素被视为 *(Mat::data + 0)
的值。然后我们添加 1 (sizeof(char)
) 并得到 *(Mat::data + 0) + 1
值。 16 位的结果等于 0x32323233。之后我们尝试从这个位置读取一些东西,这就是 SIGSEGV
的实际原因。
最好使用unsigned char*
存储数组首元素的地址,并使用已知的矩阵宽度和高度来获取合适的矩阵元素。
关于c++ - 为什么我不能访问这个 uchar 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36007946/