是否有可能在纯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;
}有没有可能给出一个数据类型作为参数,这样我就可以为该数据类型分配内存,并将其动态地转换为数组中的给定数据类型?
提前谢谢你,
Marnix van Rijswijk
发布于 2010-12-13 02:10:19
你的代码有一个严重的问题...您返回的是一个局部变量(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文件。
发布于 2010-12-13 01:56:46
伙计,这听起来真像是C++的工作。
我认为在C中最接近这一点的方法是不传递type,而是传递size (sizeof(type))。
您可以使您的函数更通用,这样如果它所知道的只是数组中每一项的大小,它就可以做它需要做的事情。像bsearch()这样的函数就是这样工作的。
发布于 2010-12-13 02:04:50
实现这一点的一种方法是使用所谓的X-macros。
Here是一个使用这种技术的(可能有buggy的)通用向量实现。
然后将其用作
// defining generic parameters
#define PREFIX tv
#define ITEM token
#define NAME token_vector
#include "vector.h"
...
token_vector tv = tv_new(100);
*(tv.front) = some_token;
tv_push_back(&tv, other_token);https://stackoverflow.com/questions/4423036
复制相似问题