是否可以在纯 ANSI-C 中复制通用数组?
我有这个结构,它包含一个数组(目前用于浮点数)和一些变量,如数组中突变的大小和容量。
typedef struct _CustomArray
{
float* array; //the array in which the objects will be stored
int size; //the current size of the array
int capacity; //the max capacity of the array
} CustomArray;
我使用这个结构,所以我可以在纯 C 中创建一个数组,我可以在其中添加/删除项目,在需要时动态扩展数组大小等等。“标准”数组所做的所有事情,除了它仅在 C 中制作。现在我想做这个,这样当你初始化这个结构时,你可以设置它应该保存的元素的数据类型,此时它只能存储浮点数据类型,但我想让它可以存储任何数据类型/其他结构。但我不知道这是否可能。
此时制作这个数组的函数是:
CustomArray* CustomArray_Create(int initCapacity, /*type elementType*/)
{
CustomArray* customArray_ptr; //create pointer to point at the structure
float* internalArray = (float*)malloc(sizeof(float) * initCapacity); //create the internal array that holds the items
if(internalArray != NULL)
{
CustomArray customArray = { internalArray, 0, initCapacity }; //make the struct with the data
customArray_ptr = &customArray; //get the adress of the structure and assign it to the pointer
return customArray_ptr; //return the pointer
}
return NULL;
}
是否可以将数据类型作为参数提供,以便我可以为该数据类型分配内存并将其动态转换为数组中的给定数据类型?
提前致谢,
马尼克斯·范·赖斯韦克