I'm trying to create a generic linked list in the C programming language and I succeeded but I have a little problem:
linked_list.h
struct Element {
void * data;
struct Element * nEl;
};
typedef struct Element Element;
struct List {
size_t el_size;
Element * start_el;
};
typedef struct List List;
linked_list.c
List * create_list(size_t el_size);
void delete_list(List * ls);
void append(List * ls, void * data);
void s_append(List * ls, void * data);
void append(List * ls, void * data) {
Element * last_el = ls - > start_el;
if (last_el == NULL)
ls - > start_el = last_el = malloc(sizeof(Element));
else {
while (last_el - > nEl != NULL)
last_el = last_el - > nEl;
last_el - > nEl = malloc(sizeof(Element));
last_el = last_el - > nEl;
}
void * cdata = malloc(ls - > el_size);
memcpy(cdata, data, ls - > el_size);
last_el - > data = cdata;
last_el - > nEl = NULL;
}
This works well with all type like int
, char
, float
, double
etc.
but it is not working with char *
because its copying the first 4 bytes
(implementation dependant) of the string
, but not the whole string
.