制作一个可以接受C语言中任何类型的动态数组 [英] Making a dynamic array that accepts any type in C

查看:68
本文介绍了制作一个可以接受C语言中任何类型的动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试寻找一种方法来构建可容纳可与任何数据类型(包括用户定义的数据类型)一起使用的动态数组的结构,

I'm trying to find a way to make a struct to hold a dynamic array that can work with any data type (Including user defined data types), so far this is what I came up with.

#define Vector(DATATYPE) struct {   DATATYPE* data; size_t size; size_t used; }

typedef Vector(int) int_Vector;

int main(int argc, char* argv[]){
    int_Vector vec;
    return 0;
}

我想知道的这是可行的做法吗?我应该做这样的事情还是有更好的方法?也有一种方法可以实现,而无需使用 typedef Vector(int)int_vector 部分。基本上,这是一种使我能够像使用c ++使用模板那样使用数组的方式,它看起来像这样:

While this works I was wondering, is this good practice? Should I be doing something like this or is there a better method? Also is there a method to implement this with out the typedef Vector(int) int_vector part. Basically a way that would enable me to use the array the same way c++ uses templates where it would look something like this:

#define Vector(DATATYPE) struct {   DATATYPE* data; size_t size; size_t used; }

int main(int argc, char* argv[]){
    Vector(int) vec;
    return 0;
}

主要是避免使用太多typedef并将它们全部放在一个名称下。

Mainly to avoid so many typedefs and have it all under one name.

推荐答案

不,C没有模板系统,所以您不能使用它。

Well no, C doesn't have a template system so you can't use one.

您可以像使用宏一样模仿效果(非常聪明的解决方案),但这当然有点不规范,需要代码的用户学习宏及其限制。

You can mimic the effects with macros like you did (pretty clever solution) but that's of course a bit non-standard and requires users of your code to learn the macro and its limitations.

通常C代码不会尝试,因为它很笨拙。

Normally C code doesn't try, since it's so awkward.

最通用的典型向量类似于glib的< a href = https://developer.gnome.org/glib/stable/glib-Arrays.html rel = noreferrer> GArray ,但是并不会假装知道每个元素的类型。而是留给用户在访问时关心,数组仅将每个元素建模为 n 个字节。

The most "generic" typical vector is something like glib's GArray, but that doesn't pretend to know the type of each element. Instead that is left to the user to care about when accessing, and the array just models each element as being n bytes.

C11中有 _Generic()可能会有所帮助,老实说,我对此并不十分有经验。

There's _Generic() in C11 which might help a bit, I'm honestly not very experienced in that.

这篇关于制作一个可以接受C语言中任何类型的动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆