![]() ![]() We start with your basic Queue type, but instead of storing an array of int, store an array of void *: typedef struct Queue I prefer this method to the preprocessor approach, though, mainly because I'm brain-damaged. I have another one that avoids using the preprocessor, but it's a lot more work, and is a poor-to-middling approximation of subclassing. Jean-François Fabre's method is a good one, and is a fair approximation of using C templates. You could create the code with a known type, debug/improve it, and then use a sed filter to generate the macro code, replacing the type by ELTTYPE and adding the #define and the trailing backslashes Output is: Front element is 1ĭrawback of this method: compilation errors on the macro code may be painful to track down. I have added 2 instanciations with 2 different types. Printf("Front element is %f\n",front_float(QF)) Printf("Front element is %d\n",front_int(Q)) * Insert the element in its rear side */ \ * As we fill the queue in circular fashion */\ * If the Queue is full, we cannot push an element into it as there is no space for it.*/\ Void Enqueue_#ELTTYPE(Queue_#ELTTYPE *Q,ELTTYPE element)\ * Return the element which is at the front*/\ * As we fill elements in circular fashion */\ĮLTTYPE front_#ELTTYPE(Queue_#ELTTYPE *Q)\ * Removing an element is equivalent to incrementing index of front by one */\ * If Queue size is zero then it is empty. Void Dequeue_#ELTTYPE(Queue_#ELTTYPE *Q)\ Q->elements = malloc(sizeof(ELTTYPE)*ma圎lements) \ Q = (Queue_#ELTTYPE *)malloc(sizeof(Queue_#ELTTYPE)) \ Queue_#ELTTYPE * createQueue_#ELTTYPE(int ma圎lements)\ Printf("Front element is %d\n",front(Q)) Įven if you aren't good friends with C , you can create a pseudo-template: #include * Insert the element in its rear side */ * As we fill the queue in circular fashion */ ![]() * If the Queue is full, we cannot push an element into it as there is no space for it.*/ * Return the element which is at the front*/ * As we fill elements in circular fashion */ * Removing an element is equivalent to incrementing index of front by one */ Q->elements = (int *)malloc(sizeof(int)*ma圎lements) How could pass to the function createQueue a struct for memory allocation without needing to know the struct previously? The struct Queue should also be changed, in int *elements the value should be changed from integer to void? #include I could create a known struct and replace all sites with integer, but this way I would be coupling the code to a known struct. I would like to modify this code to accept a struct informed by the user. Everything works perfectly, but as can be seen in the function createQueue the queue is implemented only for integers. I have a code (at the end of this post) that implements a circular queue system.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |