Making a dynamic array that accepts any type in C

后端 未结 5 1456
闹比i
闹比i 2021-01-07 18:34

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.<

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 19:05

    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.

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

    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.

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

提交回复
热议问题