0

我正在使用 CImg 库从图像中提取像素数据并将其放置在结构中的数组中:

int JpgHandle::loadJpg(const char* Name, SImageData & data){

    CImg<unsigned long> src(Name);
    int width = src.width();
    int height = src.height();
    unsigned long * pixels = new unsigned long [width*height];
    for (int r = 0; r < height; r++){
        for (int c = 0; c < width; c++){
            unsigned long pixel = (src(c,r,0,2) ) |
                                  (src(c,r,0,1) <<  8) |
                                  (src(c,r,0,0) << 16);
            *(pixels++) = pixel;
        }
    }

    data.pData = pixels;
    data.lWidth = (long) width;
    data.lHeight = (long) height;
    data.lStride = (long) width;

    return 1;
}

SImageData 是这样定义的:

struct SImageData {
    unsigned long *pData;
    long lWidth;
    long lHeight;
    long lStride;

    SImageData() : pData(NULL), lWidth(0), lHeight(0), lStride(0) {}
};

当我像这样从 main 调用 loadJpg 时:

JpgHandle handler;
SImageData data1;

handler.loadJpg(argv[1], data1);

cout << "data1: ";
for(int i = 0; i < 10; i++){
    cout << hex << data1.pData[i] << ", ";
}
cout << "\n";

它返回垃圾:

data1: 0, 1eff1, 7f226014e798, 7f226014e798, 0, 0, 0, 0, 0, 0, 

但是,如果我主要这样做:

JpgHandle handler;
SImageData data1;
SImageData data2;

handler.loadJpg(argv[1], data1);
handler.loadJpg(argv[2], data2);

cout << "data1: ";
for(int i = 0; i < 10; i++){
    cout << hex << data1.pData[i] << ", ";
}
cout << "\n";

cout << "data2: ";
for(int i = 0; i < 10; i++){
    cout << hex << data2.pData[i] << ", ";
}
cout << "\n";

结果是 data1 包含来自 argv[2] 的数据,而 data2 包含垃圾:

data1: 0, 2011, a0a0a, a0a0a, a0a0a, 90909, 90909, a0a0a, b0b0b, b0b0b, 
data2: 0, 7f0d7d712798, 0, 0, 0, 0, 0, 0, 0, 0, 

是什么赋予了?

4

1 回答 1

2

在进入嵌套循环data.pData 之前,您应该将指向已分配内存的指针保存到其中。循环递增pixels,因此它不再指向内存块的开始。

你经常打电话delete[]data.pData?这应该触发了一个错误,因为它不是从new[].

于 2013-09-13T00:17:21.390 回答