小编Com*_*der的帖子

调用new运算符时程序崩溃(C++)

我正在研究一些在C中创建ASCII游戏引擎并用C++编写程序来练习的教程.我目前正在研究一些东西,它们以Image结构的形式在堆上分配图像数据(包含int宽度,int高度,以及两个char指针指向堆上的位置,这些位置包含chars [width*height]的数组size)...但是,我在调用new运算符时遇到了一些问题.我为结构本身分配内存的函数,以及它的字符和颜色数据,如下所示:

Image *allocateImage(int width, int height) {

Image *image;
image = new Image;

if (image == NULL)
    return NULL;

image->width = width;
image->height = height;
image->chars = new CHAR[width * height];
image->colours = new COL[width * height];

//image->colours = (CHAR*) PtrAdd(image->chars, sizeof(CHAR) + width * height);

for (int i = 0; i < width * height; ++i) { //initializes transparent image
    *(&image->chars + i) = 0;
    *(&image->colours + i) = 0;
}
return image;
}
Run Code Online (Sandbox Code Playgroud)

main函数本身(此函数被调用两次)如下所示:

int main() { …
Run Code Online (Sandbox Code Playgroud)

c++ new-operator

2
推荐指数
1
解决办法
2193
查看次数

标签 统计

c++ ×1

new-operator ×1