是否可以在纯 ANSI-C 中复制通用数组?
我有这个结构,它包含一个数组(目前用于 float )和一些变量,例如数组中突变的大小和容量。
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 中创建. 现在我想做这个,这样当你初始化这个结构时,你可以设置它应该保存的元素的数据类型,此时它只能存储 float 据类型,但我想让它可以存储任何数据类型/其他结构。但我不知道这是否可能。
此时制作这个数组的函数是:
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;
}
是否可以提供一个数据类型作为参数,以便我可以为该数据类型分配内存并将其动态转换为数组中的给定数据类型?
提前致谢
马尼克斯·范赖斯韦克
最佳答案
您的代码有一个严重的问题...您正在返回局部变量 (CustomArray) 的地址,当函数返回时该变量被销毁,因此您不能继续将其与指针一起使用。您还必须 malloc 该结构,以便函数返回后内存仍然可用。
关于使类型成为参数,您可以使用宏稍微接近...例如:
#include <stdlib.h>
#define DefArray(type) \
typedef struct T_##type##Array {\
type *array; \
int size, capacity; \
} type##Array; \
static type##Array *type##ArrayCreate(int capacity)\
{\
type##Array *s = malloc(sizeof(type##Array));\
if (!s) return NULL;\
s->array = malloc(sizeof(type) * capacity);\
if (!s->array) { free(s); return NULL; }\
s->size=0; s->capacity = capacity;\
return s;\
}
然后就可以这样使用了
#include "customarray.h"
DefArray(float);
DefArray(double);
void foo()
{
floatArray *fa = floatArrayCreate(100);
...
}
请注意,您必须使用宏来定义所有自定义函数。另请注意,这种方法将复制每个模块中的代码(我认为这不是大问题,但如果您不能使用 C++,则可能您的目标平台非常小)。使用稍微复杂的方法,您可以为实现生成单独的 .h 文件和 .c 文件。
关于c - 纯 ANSI-C : make generic array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4423036/