2013-05-15 39 views
0

我有一個問題,下面的代碼(編譯器沒有抱怨,但我在運行時得到一個錯誤消息 - R6010中止)。基本上我創建了一個Image類,它從圖像中讀取數據並將其存儲在動態分配的數組中。然後我想要將圖像數據傳入int main中的另一個數組。出於某種原因,這是行不通的。C++從動態數組返回值(圖像類)

class Image 
{ 
private: 
    char* charImage; 
    int TotRows; 
    int TotCol; 
    int Size; 
    int MaxVal; 
    char Magic[2]; 

public: 
    Image(); 
    Image (const Image& Orig); 
    ~Image(); 
    void operator=(const Image&); //overloaded assignment operator 
    void ReadImage(); 
    char ReturnImage(int i); 
    int getSize(); 
}; 

Image::Image()//constructor 
{ 
    Size = (3 * TotRows * TotCol); 
    charImage = new char [Size]; 
} 

Image::Image (const Image& Orig)//copy constructor 
{ 
    TotRows = Orig.TotRows; 
    TotCol = Orig.TotCol; 
    Size = Orig.Size; 
    charImage = new char [Size]; 
} 

Image::~Image()//destructor 
{ 

    delete []charImage; 
} 

void Image::operator=(const Image& Orig) 
{ 
    TotRows = Orig.TotRows; 
    TotCol = Orig.TotCol; 
    Size = Orig.Size; 
    charImage = new char [Size]; 

    for (int i = 0; i < Size; i++) 
    { 
     charImage[i]=Orig.charImage[i]; 
    } 
} 

void Image::ReadImage() 
{ 
    //opening original image 
    ifstream OldImage; 
    OldImage.open ("image2.ppm", ios::in | ios::binary); 

    if (!OldImage) 
     cout << "\nError: Cannot open image file! " << endl; 

    //reading the header of the original image file 
    OldImage >> Magic [0] >> Magic [1]; 

    //if the image is not in the right format, do not proceed! 
    if ((Magic [0] != 'P')||(Magic [1] != '6')) 
     cout << "\nError: image is in the wrong format!" << endl; 

    else 
     OldImage >> TotRows >> TotCol >> MaxVal; 

    //reading the image in binary format and storing it in the array of characters 
    OldImage.read(charImage, Size); 

} 

char Image::ReturnImage(int i) 
{ 
    return charImage[i]; 
} 
int Image::getSize() 
{ 
    return Size; 
} 

int main() 
{ 
    char* charImage; 
    int Size; 
    Image myImage; 
    myImage.ReadImage(); 
    Size = myImage.getSize(); 

    charImage= new char [Size]; 

    for (int i=0; i<Size; i++) 
    { 
     charImage[i]=myImage.ReturnImage(i); 
    } 

    delete [] charImage; 

    return 0; 
} 

回答

0

當您創建映像(MYIMAGE)的情況下,TotRows和TotCol成員初始化。誰知道構造函數中'Size'的值是什麼。

4

一個明顯的錯誤是,你沒有設置圖像的尺寸詮釋他的默認構造函數:

Image::Image()//constructor 
{ 
    Size = (3 * TotRows * TotCol); 
    charImage = new char [Size]; 
} 

這裏,TotRowsTotCol是未初始化的,並可能有任意值。

然後,在賦值運算符中,在指向新數組之前,您不要釋放指向charImage的數組,因此您正在泄漏資源。

+0

謝謝!這完全是問題所在。非常感謝幫助我 – elrim

0

除了評論他人,

從我的理解,你不想繼續,如果圖像是不正確的 格式,但還是你讀取圖像。

//if the image is not in the right format, do not proceed! 
    if ((Magic [0] != 'P')||(Magic [1] != '6')) 
     cout << "\nError: image is in the wrong format!" << endl; 

    else 
     OldImage >> TotRows >> TotCol >> MaxVal; 

您閱讀圖像時不考慮圖像格式。

//reading the image in binary format and storing it in the array of characters 
    OldImage.read(charImage, Size); 

希望它在一定程度上有所幫助。