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 .