G
G
German2020-07-14 16:20:39
C++ / C#
German, 2020-07-14 16:20:39

Implementing a doubly linked list with elements of a specific type?

Hello.
I'm writing an implementation of a doubly linked list and I'm having trouble adding elements to it...
The element itself looks like this:

typedef struct list_item {
  struct list_item* next; //указатель на следующий элемент
  struct list_item* prev; //указатель на предыдущий элемент
  void* data_ptr; //указатель на данные
  size_t data_size; //размер данных
} list_item_t;


And here is a function that adds a new element with data:
void list_add_data(list_t* list, void* data, size_t data_size);


The problem is that I cannot add the number 10 and 12 there, for this I need to do something in the style
int num = 10;
int num2 = 12;
list_add_data(&list, &num, sizeof(int));
list_add_data(&list, &num2, sizeof(int));

or
int* num = malloc(sizeof(int));
*int = 10;
list_add_data(&list, num, sizeof(int));
num = malloc(sizeof(int));
*int = 12;
list_add_data(&list, num, sizeof(int));

And if you need to add several values, then for each value you need to create a separate variable or allocate memory and monitor it. It's obvious that it doesn't work well.

I could make a separate function for all types, a type void list_add_int(list_t* list, int data);that will allocate memory for a number and save a link, but in this case, for each possible type, I have to create a separate function instance, this is also not a solution.

Can I do something similar to data types in C++?
Something similar to vector<int> vec;and simple functions that will work with elements of the type that is required.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2020-07-31
@wataru

Unfortunately, templates were not brought to C. And, if you want to store different types in one list or use the same code to implement lists of different types, you will have to work with pointers, which means you will have to allocate memory somewhere.
It is possible in the function of adding an element to take a pointer and size, allocate new memory and copy.
This is something like your suggestion, but works for all types.
You can make 2 functions for optimization: one will copy and should be called for local variables, and the second will not copy, but will take responsibility for the passed pointer. But here you can easily make a mistake - when you call the second function, you must immediately forget the passed pointer. Otherwise, you can delete it 2 times later, or use it after deletion.
If you are going to store only ints, then it is better to rewrite the list: store not a pointer to data, but immediately int.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question