I have implemented a linked list library in C. It has all the basic functions to quickly implement a linked list. I stored all that in a header file and an implementation file.
Now I want my linked list to be able to store more information than the standard datatypes like int, char, etc.
So I build everything around a custom datatype_t
.
To give an example, this is part of the header file.
typedef int datatype_t;
typedef struct node_s
{
datatype_t key;
struct node_s *next_node_p;
struct node_s *previous_node_p;
}node_t;
//add an element to the rear of the list
int list_element_add(datatype_t new_key, list_t *list);
Now I have the problem that I want the custom datatype to be a datatype that is defined outside of the library. For example a struct. I think that is the usual case for a linked list. What options do I have to use the functions of my library.
I have implemented a linked list library in C. It has all the basic functions to quickly implement a linked list. I stored all that in a header file and an implementation file.
Now I want my linked list to be able to store more information than the standard datatypes like int, char, etc.
So I build everything around a custom datatype_t
.
To give an example, this is part of the header file.
typedef int datatype_t;
typedef struct node_s
{
datatype_t key;
struct node_s *next_node_p;
struct node_s *previous_node_p;
}node_t;
//add an element to the rear of the list
int list_element_add(datatype_t new_key, list_t *list);
Now I have the problem that I want the custom datatype to be a datatype that is defined outside of the library. For example a struct. I think that is the usual case for a linked list. What options do I have to use the functions of my library.
Share Improve this question edited Mar 31 at 12:48 Weijun Zhou 5,1662 gold badges21 silver badges41 bronze badges asked Mar 31 at 8:24 Peter KirschPeter Kirsch 695 bronze badges 4 |1 Answer
Reset to default 2Replace datatype_t
with in void*
library. This allows you to store pointers to any data type (e.g structs, ints, chars, etc.)
typedef struct node_s
{
void* key;
struct node_s *next_node_p;
struct node_s *previous_node_p;
} node_t;
int list_element_add(void* new_key, list_t *list);
since you are making the program more generic so you may face runtime error obviously, and the one who is using the library must manage memory manually using malloc/free
void *key;
andsize_t key_size;
– Some programmer dude Commented Mar 31 at 8:31typedef
. – Lundin Commented Mar 31 at 9:10<sys/queue.h>
macros. These also allow the same item to be queued on multiple lists. They work by subtracting an offset from the pointer to the list node to obtain a pointer to the containing object. – Ian Abbott Commented Mar 31 at 9:44struct node_s *next_node_p;
for? – chux Commented Mar 31 at 15:44