Reputation: 620
I am implementing a queue data structure and making it generic using void * pointer. But I am stuck at the point, as to how should I pass the data type information to get a queue of particular data type if it is even possible in C like we have templates in C++.
typedef struct queue{void * data;
struct queue * link;
}Queue;
Queue * getQueue(pass the type){
Queue * head = (Queue *)malloc(sizeof(Queue));
//cast by type the data of queue and return created queue node.
return head;
}
Queue created using malloc()
function of C. The above code creates the head of the Queue. Then other functions would create subsequent nodes on insertion request.
This is wrong, but how should I pass data type information to get it cast right, or do I have to use a _Generic macro, or is there a facility to get the type information by some other mechanism in C.
Upvotes: 2
Views: 1086
Reputation: 6404
Essentially you can't. There is no "type" variable type in C that allows you to tag a region of memory with a type specifier and then recover it.
Generally it's not needed. You know that the queue is a queue of integers, or struct employees, and simply cast the void * in calling code. The problem only comes if the queue needs a mixed set of members.
The best way is to add a string to the queue node structure representing the type. Then do an if ... else ladder on the string and cast to the right type. It's not especially efficient, but it makes the binary data human-readable. However very few queues are like that.
Upvotes: 2
Reputation: 261
Try this:
enum Type {
type0 = 0,
type1 = 1,
// and so on
};
struct Node {
void* next;
size_t size;
enum Type type;
};
struct queue {
struct Node* headNode;
};
Upvotes: 1
Reputation: 7482
There is no need for any tricks in your case. No need to bother with genericity of any kind. You are implementing a queue storing void pointers. Empty queue will be represented by NULL. Function addElement
will add a void pointer to the queue. That is all. The implementation may look like:
typedef struct queue {
void * data;
struct queue * link;
} Queue;
Queue * getQueue() {return(NULL);}
void addElement(Queue **qq, void *data) {
// find last ptr
for(; *qq != NULL; qq = &((*qq)->link) ) ;
*qq = malloc(sizeof(Queue));
(*qq)->data = data;
(*qq)->link = NULL;
}
Upvotes: 1