指针数组分配动态内存

时间:2013-12-24 09:10:07

标签: c++ dynamic-memory-allocation

标题有点过于笼统。让我直截了当。 我有一个具有大量潜在结构的应用程序,称为Player。 所以我想,让我们制作一个指向Player的指针数组,因为通常你不需要所有的玩家,而且与直接分配最大大小的数组相比,你将安全地保存动态内存,所以(C ++):

Player* a[max];
for loop

     a[i] = new Player

end

VS

Player* a;
a = new Player[max]

第一个例子是我在函数中使用的例子。每次调用该函数时,它都会在数组中分配下一个指针。一切正常,但奇怪的是,有时其中一个指针似乎失去了对堆内存的引用。当我有2个玩家并且我分配10个时,它可以工作,但过了一段时间(保证几个帧)它显示“-1.#J”作为该Player结构中浮动的值,我想这意味着它是一个未定义的值。 我无法发布整个代码(会太多),我检查了所有其他可能的错误,但我找不到一个。我开始假设它与我在一个不同的.ccp文件中使用new分配内存(因此不同的obj文件)这一事实有关。可能是这种情况吗?你可以在这种情况下使用指针数组吗?

我对使用此方法节省内存的想法可能会出错。如果是的话,请告诉我如何正确地做到这一点。

感谢。

(编辑)

产生播放器的代码(我不知道如何进行布局,对不起):

    void SpawnPlayer(float xpos, float ypos, float angle, unsigned short ammo[WP_TOTAL], unsigned char weapon)
{
    player[game.players] = new Player;
    // Properties
    player[game.players]->pos[0] = xpos;
    player[game.players]->pos[1] = ypos;
    player[game.players]->angle = angle;
    player[game.players]->dir[0] = 0.0f;
    player[game.players]->dir[1] = 0.0f;
    player[game.players]->speed = PL_SPEED;
    player[game.players]->health = PL_HEALTH;
    player[game.players]->shoot = true;
    player[game.players]->shootwait = 0;
    unsigned char i;
    CLoops(i, 0, WP_TOTAL)
    {
        player[game.players]->ammo[i] = ammo[i];
    }
    player[game.players]->weapon = weapon;
    // Model
    float cx = cos(angle) * PL_RADIUS, cy = sin(angle) * PL_RADIUS;
    player[game.players]->model.vertexcnt = 4;
    player[game.players]->model.vertex = new float[8];
    player[game.players]->model.vertex[0] = xpos - cx - cy ;player[game.players]->model.vertex[1] = ypos - cy + cx;
    player[game.players]->model.vertex[2] = xpos - cx + cy ;player[game.players]->model.vertex[3] = ypos - cy - cx;
    player[game.players]->model.vertex[4] = xpos + cx - cy ;player[game.players]->model.vertex[5] = ypos + cy + cx;
    player[game.players]->model.vertex[6] = xpos + cx  + cy ;player[game.players]->model.vertex[7] = ypos + cy - cx;    
    player[game.players]->model.texcoord = new float[8];
    player[game.players]->model.texcoord[0] = 0.0f;player[game.players]->model.texcoord[1] = 0.0f;
    player[game.players]->model.texcoord[2] = 1.0f;player[game.players]->model.texcoord[3] = 0.0f;
    player[game.players]->model.texcoord[4] = 0.0f;player[game.players]->model.texcoord[5] = 1.0f;
    player[game.players]->model.texcoord[6] = 1.0f;player[game.players]->model.texcoord[7] = 1.0f;
    core.CCreateModel(player[game.players]->model, CMODEL_TRISTRIPS, CMODEL_DYNAMIC);
    // AI
    player[game.players]->target = PL_MAXCNT;
    player[game.players]->move = 0;
    // Add global counter
    game.players++;
}

1 个答案:

答案 0 :(得分:1)

为什么不使用vectorPlayer对象指针?

std::vector<Player*> vec;

然后,当您想要分配新玩家时,请执行:

vec.push_back(new Player);

在这里,代码的问题可能是存在于数组中的任何Player都有可能被覆盖。但是,使用向量,您可以使用const iterators,因此,确保在您不希望它们时它们不会被更改。

此外,您不必担心分配常量。

此外,如果您的Player对象包含任何成员指针,请确保您没有按值传递任何Player对象或使用它们进行赋值。如果是这种情况,您可能希望编写自己的复制构造函数和赋值运算符,以便不会出现浅拷贝。