Implementing a queue using void * is good or bad practice?

I implemented the basic queue structure in C using void pointers. The procedure is as follows:

  • structure initialization - I set the size of the type of variable that should be stored in the queue
  • push - I pass a pointer to a variable to be saved, the queue then grabs a copy for myself
  • front - the structure returns void * to the front element. I can just grab a pointer or memcpy() to have a local copy.

The structure itself is as follows:

 struct queue { void* start; //pointer to the beginning of queue void* end; //-||- to the end size_t memsize; //size of allocated memory, in bytes size_t varsize; //size of a single variable, in bytes void* initial_pointer; //position of the start pointer before pop() operations }; 

the start and end are just void pointers pointing to a location within the currently allocated memory block. If I click the items in the queue, I increase the final pointer to varsize . If I pop (), I simply reduce the final pointer to varsize as well.

I don’t think I should post the function code here, it's over 100 lines.

Question: Is it considered good or bad practice? Why not)?

Note. I know that there are many other options for queuing in C. I'm just asking about the quality of this.

EDIT: Implementation is available here: http://89.70.149.19/stuff/queue.txt (remove spaces)

+6
source share
2 answers

In order of using void * , if you do not know the type and size of the objects that will be stored in the queue (in fact, the standard C library follows the same approach, see memcpy() and qsort() for some examples). However, it would be better to use size_t (or ssize_t if you need a signed data type) to indicate the size of the items stored in the queue.

+8
source

You really are not showing us enough to be sure of your implementation. void* for user data items in order, you cannot do otherwise in C.

But I strongly suspect that you have an internal type of list item that is used to manage individual items, something like

 struct list_item { struct list_item* next; void* data; }; 

If so, and your start and end pointers point to such elements, you should definitely use your element type in a struct queue declaration:

 struct queue { struct list_item* start; //pointer to the beginning of queue struct list_item* end; //-||- to the end size_t memsize; //size of allocated memory, in bytes size_t varsize; //size of a single variable, in bytes struct list_item* initial_pointer; //position of the start pointer before pop() operations }; 

To do this, you don’t even need to set the definition of a struct list_item user of struct queue .

+2
source

Source: https://habr.com/ru/post/949775/


All Articles