当我运行下面编写的程序时,出现运行时检查失败#2-变量'NewImage'周围的堆栈已损坏。我怎样才能解决这个问题?我知道这与超出变量的内存限制有关,但我不确定要更改什么。谢谢!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int ROWS = 16;
const int COLS = 16;
enum flipType {HORIZONTAL, VERTICAL};
enum rotateType {CLOCKWISE, COUNTER_CLOCKWISE};
void getImage(char img[][COLS]);
void print(const char img[][COLS], string msg);
void flip(const char img[][COLS], char NewImage[][COLS], flipType);
void negative(const char img[][COLS], char NewImage[][COLS]);
void rotate(const char img[][COLS], char NewImage[][COLS], rotateType);
int main()
{
char Image[ROWS][COLS];
char NewImage[ROWS][COLS];
getImage(Image);
// print the original image
print(Image, "Original Image");
getImage(NewImage);
flip(Image, NewImage, VERTICAL);
print(NewImage, "Vertically Flipped Image");
getImage(Image);
flip(Image, NewImage, HORIZONTAL);
print(NewImage, "Horizontally Flipped Image");
getImage(Image);
negative(Image, NewImage);
print(NewImage, "Negative Image");
getImage(Image);
rotate(Image, NewImage, CLOCKWISE);
print(NewImage, "Clockwise Rotated Image");
getImage(Image);
rotate(Image, NewImage, COUNTER_CLOCKWISE);
print(NewImage, "Counter-Clockwise Rotated Image");
return 0;
}
void getImage(char img[][COLS])
{
char discard;
//Load image from file
ifstream imgFile;
imgFile.open("16X16L.txt");
for (int i=0; i<ROWS; i++)
{
for (int j=0; j<COLS; j++)
{
char inputChar;
imgFile.get(inputChar);
// Convert digital to blank or asterisk
if (inputChar == '0')
img[i][j] = ' ';
else
img[i][j] = '*';
}
// throw away the newline character
imgFile.get(discard);
}
}
void print(const char img[][COLS], string msg)
{
cout << msg << endl;
for (int i=0; i < ROWS; i++)
{
for (int j=0; j < COLS; j++)
{
cout << img[i][j];
}
cout << endl;
}
}
void flip(const char img[][COLS], char NewImage[][COLS], flipType flipDir)
{
if(flipDir == HORIZONTAL)
{
for (int i=0; i<ROWS; i++)
{
for (int j=0; j<COLS; j++)
{
NewImage[i][-j-1]= img[i][j];
}
}
}
else if (flipDir == VERTICAL)
{
for (int i=0; i<COLS; i++)
{
for (int j=0; j<ROWS; j++)
{
NewImage[ROWS-1-i][j]= img[i][j];
}
}
}
}
void negative(const char img[][COLS], char NewImage[][COLS])
{
for (int i=0; i<ROWS; i++)
{
for (int j=0; j<COLS; j++)
{
if (img[i][j] == ' ')
NewImage[i][j] = '*';
else NewImage[i][j] = ' ';
}
}
}
void rotate(const char img[][COLS], char NewImage[][COLS], rotateType rotateDir)
{
if (rotateDir == CLOCKWISE)
{
for(int i=0; i<COLS; i++)
{
for(int j=0; j<ROWS; j++)
{
NewImage[i][j] = img[ROWS-1-j][i];
}
}
}
else
{
for(int i=0; i<COLS; i++)
{
for(int j=0; j<ROWS; j++)
{
NewImage[i][j] = img[j][COLS-1-i];
}
}
}
}
最佳答案
取代这个
NewImage[i][-j-1]= img[i][j];
有了这个
NewImage[i][COLS-j-1]= img[i][j];
不知道为什么自从正确翻转垂直后就无法发现自己,并且对问题所在有很好的了解。我想需要学习仔细查看自己的代码。
关于c++ - C++调试错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20141761/