C++ EasyBMP 指针问题
以下代码导致 .ReadFromFile 行出现分段错误:
int main()
{
// Load in.bmp
BMP * original;
cout << "line " << __LINE__ << ": Got here!" << endl;
original->ReadFromFile("in.bmp"); //Error HERE!
int width = original->TellWidth();
int height = original->TellHeight();
cout << "line " << __LINE__ << ": Got here!" << endl;
我正在使用 EasyBMP 库,它包含在主函数上方。我知道它与内存和指针有关,但我不知道用什么来代替“原始->”......我已经尝试过(*原始)。和(&原始)。但我似乎无法理解。有什么帮助吗?
谢谢!
The following code is causing a Segmentation Fault on the .ReadFromFile line:
int main()
{
// Load in.bmp
BMP * original;
cout << "line " << __LINE__ << ": Got here!" << endl;
original->ReadFromFile("in.bmp"); //Error HERE!
int width = original->TellWidth();
int height = original->TellHeight();
cout << "line " << __LINE__ << ": Got here!" << endl;
I'm using the EasyBMP library, which is included above the main function. I know it has something to do with memory and pointers, but I can't figure out what to use in place of "original->"... I've tried (*original). and (&original). but I can't seem to get it. Any help?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的指针
original
指向随机内存位置。尝试使用它会导致未定义的行为。您需要为BMP
对象分配内存并将地址存储在该指针中。如果您希望对象在退出函数后仍然保留,请使用original = new BMP();
(但不要忘记稍后删除
它),否则您可以直接做BMP原图
并使用。Your pointer
original
is pointing to a random memory location. Trying to use it will cause the undefined behavior. You need to allocate memory forBMP
object and store the address in this pointer. If you want your object to persist even after it goes out of the function useoriginal = new BMP();
(don't forget todelete
it later though) else you can directly doBMP original;
and use it.您已将 BMP 声明为指针但从未初始化它。
尝试使用:
或
第一个方法将在堆栈上创建原始内容,并且您不必释放它。第二种方法在免费存储中创建它,您需要使用删除来释放它。
You have declared BMP as a pointer but never initialized it.
Try using:
or
The first method will create original on the stack, and you won't have to release it. The second method creates it in the free-store, and you need to use delete to free it.
根据教程,您的代码应该是:
According to the tutorial, your code should be:
没有必要使用指针,请尝试以下操作:
或者如果您需要使用堆,请执行以下操作:
完成后不要忘记释放内存
It is not necessary to use a pointer try this:
or if you need to use the heap do:
and when you are done don't forget to free the memory