是否有可能在纯 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制作的。 现在我想让初始化这个结构体时,可以设置它应该容纳的元素数据类型,目前它只能存储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;
}
是否可能将数据类型作为参数传递,以便我可以动态地为该数据类型分配内存,并将其强制转换为给定的数据类型在数组中?
提前致谢,
Marnix van Rijswijk
_Pragma
、_Complex
、_Bool
等);一个简单的解决方法是使用尾随下划线,这也可以与基于前缀的命名空间很好地配合使用。 - Christophsizeof
和链接中讨论的函数指针机制,您可以实现所需的结果,但这将是一项更加艰巨的工作。qsort
和bsearch
的接口是一种折衷方案。 - dmckee --- ex-moderator kitten