I want to create a generic stack. I want to implement it with a linked-list.
I created this structures stack_l :
typedef struct stack
{
void * data;
void (*copy)(void *o);
struct stack *next;
} stack_l;
I have some questions:
- The second field of the structures is a pointer to a function, to copy a new data (passing by argument in a function Push).
The prototype of the function Push is:
stack_l * Push( stack_l * head, void * d );
- Is it correct how I pass the pointer to the function copy?
- I have to implement it in the function Push??
- Is it necessary create a function NewStack (for example) to inizialize the field of the structures, or is better have only a Push function that create the 1st element if the stack is empty, and add new element on top if there is at least one element?
- A void * need to be allocated with a malloc ?
First of all, you do not require different identifiers for
stackandstack_l. Now, to your questions:Your
Pushfunction is incompatible with the type of thecopyfield instack_l. If you want to include a pointer to (member-)functions in yourstructto make it look like C++, you still have to pass your object to these functions.Yes ,you have to implement your functionality somewhere, and that cannot be within the definition of
struct stack. This means that you do need some sort of constructor function (you may call itnewStackif you like). Your constructor must at least initialise your function pointers (if you want to keep them). If you opt not to keep these function pointers you can put the initialisation code well in yourpushroutine, as you suggested:Note that you have to explicitly state what the empty stack is. So you may want to implement a constructor for clarity:
And maybe even a destructor:
To your last question: As you see above, you have to use
mallocto get space to hold yourstack_lobject, other than that, you do not need to allocate extra space for yourvoid*member, as it is part ofstack_l.