我以两种不同的方式编写代码:使用二维数组作为矩阵,以及使用 boost::ublas::matrix。当我在第一种情况下添加这个对象时,它正在工作,但在第二种情况下,我遇到了分段错误。我想使用第二种方式,所以如果有人知道我为什么会出现段错误,我将不胜感激。
编码:
img.h
#include <Magick++.h>
#include <string>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
using namespace boost::numeric::ublas;
using namespace std;
using namespace Magick;
class Img
{
public:
Img();
Img(const string path2file);
unsigned int width, height;
string filename;
private:
typedef struct pix
{
Quantum R;
Quantum G;
Quantum B;
} pix;
matrix<pix> p;
pix **pixels;
string format;
};
img.cpp
Img::Img(const string path2file)
{
Image file;
unsigned int i, j;
Color pixel;
file.read(path2file);
filename = path2file;
width = file.size().width();
height = file.size().height();
// begin of first way
pixels = (pix**)malloc(sizeof(pix*)*height);
for(i=0 ; i<height ; ++i)
pixels[i] = (pix*)malloc(sizeof(pix)*width);
for(i=0 ; i<height ; ++i)
{
for(j=0 ; j<width ; ++j)
{
pixel = file.pixelColor(j, i);
pixels[i][j].R = pixel.redQuantum();
pixels[i][j].G = pixel.greenQuantum();
pixels[i][j].B = pixel.blueQuantum();
}
}
// end of first way
// begin of second way
p.resize(height, width);
for(i=0 ; i<height ; ++i)
{
for(j=0 ; j<width ; ++j)
{
pixel = file.pixelColor(j, i);
p(i, j).R = pixel.redQuantum();
p(i, j).G = pixel.greenQuantum();
p(i, j).B = pixel.blueQuantum();
}
}*/
}
// end of second way
我很确定这段代码不是段错误的原因。但是当我在主程序中使用它时,我遇到了段错误(仅适用于第二种方式,第一种方式有效):
主文件
#include <iostream>
#include <stdio.h>
#include "img.h"
#include <vector>
using namespace std;
int main(void)
{
std::vector<Img> files;
files.push_back(Img("files/mini.bmp"));
return 0;
}