General data structure in C

Is there a way to create a common data structure in C and use functions according to the stored data type, a structure that has different data types and, for example, can be printed according to the stored data.

For example,

Suppose I want to create a binary search tree that has only float's, int is stored. A natural approach to this would be to create an enum with int and float. it would look something like this:

Typedef enum {INT, FLOAT} DataType;

Typedef struct node
{
    void *data;
    DataType t;
    struct node *left,
                *right;
}Node;

if I want to print it:

void printTree(Node *n)
{
    if (n != NULL)
    {
        if (n->t == INT)
        {
            int *a = (int *) n->data;
            printf("%d ", *a);
        }
        else
        {
            float *a = (float *) n->data;
            printf("%f ", *a);
        }

        printTree(n->left);
        printTree(n->right);
    }
}

This is fine, but I want to save the other data type as a stack, query, or something else. Therefore, I created a tree that does not depend on a specific data type, for example:

Typedef struct node
{
    void *data;
    struct node *left,
                *right;
}Node;

If I want to print it, I use callback functions, for example:

Node *printTree(Node *n, void (*print)(const void *))
{
    if (n != NULL)
    {
        print(n->data);
        printTree(a->left);
        printTree(a->right);
    }
}

, float . : , , , ? , int float, , , ?

: node , , , .h .c .

+4
3

C /. , :

  • Clang , C. , , .

  • ++

  • print, -

    struct data_info {
      void *data;
      enum_describing_type type;
    }
    

    print printInt, printFloat ..

+1

- . , Node tagged union, , , . Node - , print, printf.

typedef enum {POINTER, INT, FLOAT} DataType;

typedef struct node
{
    DataType t;
    union {
        void *pointer;
        int integer;
        float floating;
    } data;
    struct node *left,
                *right;
} Node;

void printTree(Node *n, void (*print)(const void *))
{
    if (n != NULL) {
        switch (n->t) {
            case POINTER:
                print(n->data.pointer);
                break;
            case INT:
                printf("%d ", n->data.integer);
                break;
            case FLOAT:
                printf("%f ", n->data.floating);
                break;
        }
        printTree(a->left, print);
        printTree(a->right, print);
    }
}
+4

uthash - , -, .., C.

0

All Articles