如何使用 void** 和 void* 创建动态数组?
How make a dynamic array using void** and void*?
我想创建一个动态内存数组函数,我可以在参数中放入我想要的任何类型、计数和我想要的项目。我一直在谷歌搜索和观看 YT 视频,但其中 none 解释了如何做到这一点,以及我想要的项目何时是指针。例如,我会这样:
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,但要么使程序崩溃,要么什么都不做。 new 和 delete 对这类东西有用吗?
删除这样的东西如何工作?我还没有在互联网上看到任何关于从列表中删除项目的信息,只是添加它们。
谢谢!
使用双指针作为数据类型,例如 int**
可以为您提供动态二维数组或指针对象的动态数组,具体取决于您的实现,而单个 int*
是只是一个普通的动态数组。要为它们完全实例化和分配内存,请按以下步骤操作:
一维动态数组:
int* arr;
arr = new int[SIZE];
二维动态数组:
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];
我想创建一个动态内存数组函数,我可以在参数中放入我想要的任何类型、计数和我想要的项目。我一直在谷歌搜索和观看 YT 视频,但其中 none 解释了如何做到这一点,以及我想要的项目何时是指针。例如,我会这样:
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,但要么使程序崩溃,要么什么都不做。 new 和 delete 对这类东西有用吗?
删除这样的东西如何工作?我还没有在互联网上看到任何关于从列表中删除项目的信息,只是添加它们。
谢谢!
使用双指针作为数据类型,例如 int**
可以为您提供动态二维数组或指针对象的动态数组,具体取决于您的实现,而单个 int*
是只是一个普通的动态数组。要为它们完全实例化和分配内存,请按以下步骤操作:
一维动态数组:
int* arr;
arr = new int[SIZE];
二维动态数组:
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];