Making a dynamic array that accepts any type in C

后端 未结 5 1482
闹比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

    Not bad. And I don't see any disadvantage. Just to explain another method, mostly common used in this case use union:

    typedef union { int i; long l; float f; double d; /*(and so on)*/} vdata;
    typedef enum  {INT_T,LONG_T,FLOAT_T, /*(and so on)*/} vtype;
    typedef struct 
    {
        vtype t;
        vdata data
    } vtoken;
    typedef struct
    {
        vtoken *tk;
        size_t sz;
       size_t n;
    } Vector;
    

    So this is possible way. The enum of datatype, you can avoid with typedefs, but if you use mixed (ex: sum long, to double, to float and so on) you must use them, since int + double is not equal to double+int; This is also a reason, because is more easy to see unions do this job. You leave al the arithmetic rules untouched.

提交回复
热议问题