我现在正在做作业。有一件事让我困惑,我需要你的建议。 这个问题对于内存分配来说非常简单和基本。学习C语言后,我正在学习C++入门书。所以我更喜欢使用new
和delete
来做内存分配,这让我无法解决这个问题。这是问题。功能getNewFrameBuffer
用于为framebuffer : (sizeof)Pixel x width x height
分配分配内存,请注意Pixel
是用户定义的数据类型。然后返回分配内存的指针。如何分配内存使用C++而不是C malloc
char* m_pFrameBuffer;
int width = 512, int height = 512;
//function call
getNewFrameBuffer(&m_pBuffer, width, height);
//function implementation using malloc
int getNewFrameBuffer(char **framebuffer, int width, int height)
{
*framebuffer = (char*)malloc(sizeof(Pixel) * width *height);
if(framebuffer == NULL)
return 0;
return 1;
}
然而,当我尝试使用新的关键字来分配内存会导致程序意外终止:当我使用如下malloc()
功能,它工作正常。这里是我的代码:
int getNewFrameBuffer(char **framebuffer, int width, int height)
{
framebuffer = new char*[sizeof(Pixel) * width *height];
if(framebuffer == NULL)
return 0;
return 1;
}
我的代码有什么问题?非常感谢所有人:)
谢谢黑暗,你指出了问题,并提供了一个解决方案:)我会小心,并尽我所能找出我想分配。谢谢! – Zengrui 2014-08-29 02:30:19
这样做的更多C++方法将是“新像素[宽度*高度]” – Beanz 2014-08-29 03:13:16
更多的C++方式这样做是'std :: vector(width * height)'。 –
chris
2014-08-29 03:22:18