Is it possible to imitate python tuples in C? -


I want to know what the strategy is? (If strategies are present).

can hold one of the different basic types to implement the object A typical pattern in C is that an element using a struct can be stored for possible basic types of union , and an element that is enum < / Code> recognizes

then you can use an array of such objects, possibly showing as a struct Is. There are many items, and an indicator for the storage of those items.

For example something like this:

#include & lt; Stdio.h & gt; # Include & lt; Stdlib.h & gt; Typefif enum Tupal_datatp_i {TUPLE_DATATYPE_INT, TUPLE_DATATYPE_FLOAT, TUPLE_DATATYPE_STRING} tuple_datatype_t; Typewrift straight tuple_item_s {tuple_datatype_t datatype; Union {int int_val; Float float_value; Four * string_value; } U; } Tuple_item_t; Typedef struct tuple_s {unsigned int n_items; Tuple_item_t * items; } Tuple_t; Static zero print_tuple (tuple_t * t) {unsigned int i; For printf ("("); (i = 0; i & lt; t-> n_items; i ++) {if (i>; 0) printf (","); switch (t-> ; Item [i] datatype) {case TUPLE_DATATYPE_INT: printf ("% d", t-> item [i] .u.int_val); break; case TUPLE_DATATYPE_FLOAT: printf ("% f", t- & gt; Item [i] .u float_value) break; case TUPLE_DATATYPE_STRING: printf ("\"% s \ "", t-> item [i] .u.string_val); break;}} printf (") \ n "); } Int main {zero} {tuple_t foo; Foo.n_items = 3; Foo.items = malloc (size (tuple_item_t) * foo.n_items); Foo.items [0] .datatype = TUPLE_DATATYPE_INT; Foo.items [0] .u.int_val = 123; Foo.items [1] .datatype = TUPLE_DATATYPE_FLOAT; Foo.items [1] .u.float_val = 4.56; Foo.items [2] .datatype = TUPLE_DATATYPE_STRING; Foo.items [2] .u.string_val = "78 9"; Print_tuple (& amp; foo); Return 0; }

Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -