如何使用void **和void *制作动态数组?

时间:2015-11-20 00:56:51

标签: c++ arrays memory dynamic

我想创建一个动态内存数组函数,在参数中我可以放入任何我想要的类型,计数和我想要的项目。我一直在谷歌搜索和观看YT视频,但没有一个解释如何做到这一点,当我想要的项目是一个指针。例如,我会这样:

struct Entity
{
   int health;
   int level;
   int experience;
   char* name;
}

Entity** entitylist = NULL;
int entitycount = 0;

Entity* CreateEntity(/*args for creating an entity*/)
{
   Entity* newentity = malloc(sizeof(Entity));
   // All of the entity creation stuff and at the end...
   AddItemToList(&Entity, &newentity, &entitycount);
}

我知道在我想要创建的函数中,我需要传递对特定列表的引用,但从中我非常无能为力。我试过使用malloc和realloc,但要么崩溃程序,要么什么都不做。新的和删除会为这类东西工作吗?

如何删除像这样的工作?我还没有在互联网上看到有关从列表中删除项目的任何内容,只添加它们。

谢谢!

1 个答案:

答案 0 :(得分:0)

使用双指针为int**等数据类型提供动态2D数组,或指针对象的动态数组,具体取决于您的实现,而单个int*只是一个正常的动态数组。要完全实例化并为这些内容分配内存,请按以下步骤操作:

1D动态数组:

int* arr;
arr = new int[SIZE];

2D动态数组:

int** arr;
arr = new int*[SIZE]; //<- stop here for 1D array of pointer objects
for (int i = 0; i < SIZE; i++)
    arr[i] = new int[SIZE2];