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
If you want to print a data in the correct format, you must know what is its type.
#include <stdio.h>
enum datatype
{
DATATYPE_STRING, DATATYPE_INTEGER
};
struct record
{
enum datatype type;
void *data;
struct record *next;
};
void print_record(struct record *p)
{
switch (p->type)
{
case DATATYPE_STRING:
printf("%s\n", (char *)p->data);
break;
case DATATYPE_INTEGER:
printf("%d\n", *(int *)p->data);
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With