分配我用指针删除2d数组

时间:2016-02-04 00:23:51

标签: c

我不知道我做错了什么。我有那个main():

int main(int argc, char argv[])
{

    Player ** player = NULL;
    int sizePlayer = STARTPLAYER;

    CreateMemoryPlayer(&player,sizePlayer);    

    DeleteMemoryPlayer(&player, sizePlayer);
    return 0;
}

这是创建功能:

void CreateMemoryPlayer(Player *** player,int size)
{
    Player ** tmpPlayer = *player;

    tmpPlayer = (Player **)calloc(size, sizeof(Player*));
    for (int i = 0; i < size; i++)
        tmpPlayer[i] = (Player*)calloc(1, sizeof(Player));
}

删除:

void DeleteMemoryPlayer(Player *** player,int size)
{
    Player ** tmpPlayer = *player;
    for (int i = 0; i <size ; i++)
        free(tmpPlayer[i]);
    free(tmpPlayer);
}

我认为这很好,但程序崩溃了。我真的不知道这段代码可能有什么问题。请帮帮我。

2 个答案:

答案 0 :(得分:1)

如果我看到这一点,CreateMemoryPlayer()中分配的内存只分配给局部变量tmpPlayer,但是你永远不会更新将引用传递给它的参数变量player。将内存分配回main()方法。

更好的模式是编写这两种方法,使得它们可以像这样使用:

Player ** player = CreateMemoryPlayer(sizePlayer);
DeleteMemoryPlayer(player, sizePlayer);

答案 1 :(得分:1)

您应该返回Player数组,而不是通过指针传递它。

Player **creatplayer(size_t size)
{
    Player **ret;
    size_t i;

    if ((ret = calloc(1, sizeof (Player *))) == NULL)
        return NULL;

    for (i = 0; i < size; ++i)
        if ((ret[i] = calloc(1, sizeof (Player))) == NULL)
            return NULL;

    return ret;
}
void delplayer(Player **p, size_t size)
{
    size_t i;
    for (i = 0; i < size; ++i)
        free(p[i]);
    free(p);
}