title: generic data structure in C
body: <p>Is there any way to create generic data structure in C and use functions in accordance with the stored data type, a structure that has various types of data and for example can be printed according to the stored data.</p>
  
  <p>For example,</p>
  
  <p>Suppose I wish to make a binary search tree that has just float's, int's stored. The natural approach to do would be to create an enumeration with int's and float's. it would look something like this:</p>
  
  <pre><code>Typedef enum {INT, FLOAT} DataType;
  
  Typedef struct node
  {
      void *data;
      DataType t;
      struct node *left,
                  *right;
  }Node;
  </code></pre>
  
  <p>if i want print it out: </p>
  
  <pre><code>void printTree(Node *n)
  {
      if (n != NULL)
      {
          if (n-&gt;t == INT)
          {
              int *a = (int *) n-&gt;data;
              printf("%d ", *a);
          }
          else
          {
              float *a = (float *) n-&gt;data;
              printf("%f ", *a);
          }
  
          printTree(n-&gt;left);
          printTree(n-&gt;right);
      }
  }
  </code></pre>
  
  <p>That's ok but i want to store another data type as a stack, query or something else. So that's why I created a tree that does not depends on a specific data type, such as:</p>
  
  <pre><code>Typedef struct node
  {
      void *data;
      struct node *left,
                  *right;
  }Node;
  </code></pre>
  
  <p>If i want to print it out i use callback functions, such as:</p>
  
  <pre><code>Node *printTree(Node *n, void (*print)(const void *))
  {
      if (n != NULL)
      {
          print(n-&gt;data);
          printTree(a-&gt;left);
          printTree(a-&gt;right);
      }
  }
  </code></pre>
  
  <p>But it falls down when i try to insert a integer and a float and print it out. My question is, Is there a way of creating a generic data structure that a routine depends on a specific data type in one situation but another situation it doesn't , for mixed data type? In this situation i should create a structure that stores int's  and float's stores it and use a print function like in the first print code for that in the callback function?</p>
  
  <p><em>observation: I just declared a node in the structure and did everything on it trying to simplify, but the idea is to use the structure with .h and .c and all this abstraction involving data structures.</em></p>