I am wondering if this is even possible, but can you use void pointers to implement a generic stack (or any other generic structure). For example, I am t开发者_开发知识库rying out the code below code. The functions for push and pop compile, but I don't understand how to handle them in main.
I am wondering if this is even possible? When you create a void pointer as I do in the structure definition, that is not allocating any actual storage for data is it? For example, in the push routine:
elem->data = data; //This is not creating any new storage, data points to existing variable
It would seem to me that the only way to do something like this in C is to pass a void pointer and have if statements which separately handle each datatype (the datatype has to be passed as an input)? Is that right?
typedef struct Element {
struct Element *next;
void *data;
} element;
typedef element * element_ptr;
typedef void * void_ptr;
typedef int * int_ptr;
void pop (element_ptr *stack, void_ptr *data)
{
element *elem;
elem = *stack;
*data = elem->data;
*stack = elem->next;
free(elem);
}
void push (element_ptr *stack, void *data)
{
element *elem;
elem = (element *) malloc(sizeof(element));
elem->data = data;
elem->next = *stack;
*stack = elem;
}
main()
{
element *stack;
void *data;
int num, num2;
int_ptr num_ptr;
num_ptr = &num2;
num = 5;
push(&stack,&num);
pop(&stack,&num_ptr); //This line gives a warning
printf("Popped %d from stack\n",num2); //Does not work.
}
First off, a void *
can be used as a place holder for any pointer type. I'm not entirely sure what you are asking, but if you want a stack of int
, then you can create your object (on the heap), then pass a pointer to the int to the push method - but you must cast the pointer to void
:
void * void_ptr = (void*)pointer_to_int
The tricky part is casting back to int
when you pop - this requires knowing that the stack holds int
and not float
etc.
Hope that helps.
精彩评论