I am trying to implement a generic stack in c using void pointer to point to the data. the structure looks like this
struct record{
void* data;
struct record* previousRecord;
};
where void pointer data is a pointer to the data a stack position will hold. If I implement a push function like this
struct record* push(struct record* tos, void* data){
struct record* newtos = (struct record*)malloc(sizeof(struct record));
newtos->data = data;
newtos->previousRecord = tos;
return newtos;
}
and push a couple of integer pointers and string pointers into the stack, is there any way I can print the values referenced by these pointers. My problem is that I have to specify the data type of value to print in the code if I use a printf function but the values stored in the stack can only be determined at run time
With address how would you know the type of data, it can be string or an integer address:
But you can keep an extra field in your
recorddefinition about type of value stored indata part, like below:and write a common print function :
Here is a Project/A book that can be very helpful to write generic code in C.