我正在使用 malloc 分配三个矩阵(matR、matG、matB)并为它们分配 vector 的一些值 图片。 像往常一样,我使用两个整数 (i, j) 来为这项工作创建循环。第一次,当i=0和j=0时,它赋值如下:197给matR[0][0],211给matG[0][0],219给matB[0][0]。到现在为止还可以。这些是我想要的值(value)观。但是这里出现了奇怪的行为:在某些点上,新值被分配给 matR[0][0]、matG[0][0]、matB[0][0]!
这是执行我所说的代码的一部分:
int i, j, k;
std::vector<unsigned char> image; //the raw pixels
unsigned error = lodepng::decode(image, width, height, filename);
matR = (unsigned char**)malloc(sizeof(unsigned char)*width);
matG = (unsigned char**)malloc(sizeof(unsigned char)*width);
matB = (unsigned char**)malloc(sizeof(unsigned char)*width);
k=0;
for(i=0; i<width; i++) {
matR[i] = (unsigned char*)malloc(sizeof(unsigned char)*height);
matG[i] = (unsigned char*)malloc(sizeof(unsigned char)*height);
matB[i] = (unsigned char*)malloc(sizeof(unsigned char)*height);
for(j=0; j<height; j++) {
matR[i][j] = image[k++];
matG[i][j] = image[k++];
matB[i][j] = image[k++];
k++; //separator
}
我添加了一些代码来调试代码,然后在终端上运行,我得到了以下输出: http://imgur.com/XvQIGYk
*说明当i=100,j=0时,matR[0][0]的值变为176。
这是怎么回事?
最佳答案
这一行:
matR = (unsigned char**)malloc(sizeof(unsigned char)*width);
应该是:
matR = (unsigned char**)malloc(sizeof(unsigned char *)*width);
// Note here ^
您正在为 width
字符分配空间,而不是 width
指针。糟糕。
但是,既然你已经用 c++
标记了它,你为什么不写:
std::vector<std::vector<char>> matR(width, std::vector<char>{height});
(有更好的方法来编写矩阵类,但这比自己编写 malloc 更好。)
关于c++ - 为矩阵赋值时的奇怪行为 (C/C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218843/