gpt4 book ai didi

C++ 指针和数组

转载 作者:行者123 更新时间:2023-11-28 02:29:04 24 4
gpt4 key购买 nike

我对动态数组有疑问。

在头文件类中我有这个:

class CTerrain
{
...
CRock *rocks;
int numRocks;//=0
...
}

在 cpp 中我有这个:

void CTerrain::Create()
{
numRocks = 0;
int NUM_ROCKS = rand()%10+1;
for(int i=0;i<NUM_ROCKS;i++)
{
rocks = new CRock;
numRocks++;
...
}
}
void CTerrain::Render()
{
for(int i=0;i<numRocks;i++)
rocks[i].render();//it works ok when here is 0 instead of 'i'
}

当我运行这段代码时出现错误:OpenGL.exe 中 0x00913aea 处未处理的异常:0xC0000005:访问冲突读取位置 0x1c00001f。

感谢您的帮助,我已经尝试解决这个问题大约 4 个小时...

编辑:

好的,所以我将 Create() 方法更改为:

void CTerrain::Create()
{
numRocks = 0;
int NUM_ROCKS = rand()%10+1;
rocks = new CRock[NUM_ROCKS];
for(int i=0;i<NUM_ROCKS;i++)
{
rocks[i].position = ...
numRocks++;
...
}

并且还添加了 delete [] rocks,现在可以正常工作了。

最佳答案

您的Create 函数更像是

void CTerrain::Create()
{
int NUM_ROCKS = rand()%10+1;
rocks = new CRock[NUM_ROCKS];
numRocks = NUM_ROCKS;
for(int i=0; i<NUM_ROCKS; i++)
{
rocks[i] = CRock{};
}
}

关于C++ 指针和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29478907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com