overexchange overexchange - 1 year ago 82
C Question

What is the data model required for such data?

Using python syntax, we have deep list like,

Example 1 -

list = [1, [2, 3], 4]

Example 2 -
list = [[1, [1, 1]], 1, [1, 1]]

where each subset MUST be of class
at runtime.

Using C language, What is the data model required to maintain such data?

Note: Dimensions are not fixed, as per the example

Answer Source

Use a forward declaration of a structure for the elements.

// declare existence of a structure type to be used for array elements.
struct some_type_S;

// The list type is a count and pointer to an array of `struct some_type_S`
// Alternative: use a variable length array for `element`
typedef struct list_S {
  size_t num_elements;
  struct some_type_S *element;
  // Alternative: use C99 and a variable length array for `element`
  // struct some_type_S element[];
} list_T;

// Now define `struct some_type_S` as
// a flag (is_int) and a union of an `int` and a pointer to a list
typedef struct some_type_S {
  _Bool is_int;
  union {
    int i;
    list_T *list;
  } u;
} some_type_T;

Happy C coding.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download