纯ANSI-C:制作通用数组

Mar*_* R. 4 c arrays generics typeof dynamic-typing

是否可以在纯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; 
Run Code Online (Sandbox Code Playgroud)

我使用这个结构,所以我可以在纯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;
}
Run Code Online (Sandbox Code Playgroud)

是否可以将数据类型作为参数提供,以便我可以为该数据类型的malloc内存并将其作为动态数组中的给定数据类型进行转换?

提前致谢,

Marnix van Rijswijk

650*_*502 7

你的代码有一个严重的问题...你正在返回局部变量的地址(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;\
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以这样使用它

#include "customarray.h"
DefArray(float);
DefArray(double);

void foo()
{
    floatArray *fa = floatArrayCreate(100);
    ...
}
Run Code Online (Sandbox Code Playgroud)

请注意,您必须使用宏来定义所有自定义函数.另请注意,此方法将复制每个模块中的代码(我说不是一个大问题,但如果您不能使用C++,则可能您的目标平台非常小).使用稍微复杂的方法,您可以为实现生成单独的.h文件和.c文件.

  • 呵呵......欢迎来到元编程世界(编写代码编写代码).C预处理器是一种非常弱的元编程形式,C++模板机制只是稍微好一些.对于真正的魔法你要使用外部生成器(例如在python/perl中编写C/C++生成器很容易)或者转移到其他语言可以使用严格的元编程(例如Lisp). (3认同)