我一直在创建一个类,它获取一堆图像并将它们叠加到一个 BMP 上。出于某种原因,在运行代码时我遇到了段错误,并且我已经将其追踪到此方法。本质上,if 语句检查图像数组中是否有一个有效的索引来放置这个新图像。如果它是有效的,那么它会删除以前存在的所有内容并将该索引设置为这个新图像。该类称为场景,由一组图像指针组成。所以我正在做的是替换其中一个指针指向的图像。不知何故,它不起作用。如果指针为 NULL,则删除命令不会导致任何问题,因此我看不出哪里出了问题。此代码作用于具有长度为 5 的图像指针数组的场景。
void Scene::addpicture(const char* FileName, int index, int x, int y)
{
if (index<0 || index>maxnum-1)
{
cout << "index out of bounds" << endl;
}
else
{
Image* extra;
extra = new Image;
extra->ReadFromFile(FileName);
delete imagelist[index];
imagelist[index] = extra;
imagelist[index]->xcoord=x;
imagelist[index]->ycoord=y;
}
}
谁能帮忙。将不胜感激。
谢谢
我已经编辑以包含构造函数:
Scene::Scene(int max)
{
Image** imagelist = new Image*[max];
for(int i=0; i<max; i++)
{imagelist[i] = NULL;}
maxnum = max;
}
我还注释掉了 main 方法,这样唯一被调用的函数是
Scene* set = new Scene(5);
set->addpicture("in_01.bmp", 0, 0, 0);
最佳答案
在您的构造函数中,您有一个本地镜像列表,但您在 addpicture 中使用了一个字段图像列表。您正在隐藏构造函数中的 imagelist 字段,并且该字段永远不会被初始化。
通过替换这一行来修复它:
Image** imagelist = new Image*[max];
有了这个:
imagelist = new Image*[max];
关于c++ - 调用删除时的总线错误 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2226198/