Ok, so I made a linked list in C, and I'm trying to make it store datatypes that the List doesn't necessarily know about (I guess generic programming?). So far I have tried using the datatype "void" to accomplish this and it "kind of" works. I'll explain it down below. I'm not sure what the problem is, or if my method of doing this is even possible.
Below is some of the code which is outside of the Linked List
Note: I do eventually want to store more than a single integer in Node, but for simplicity/testing this is what I have:
Code:
typedef struct Node {
int value;
} Node;
typedef Node* NodeRef;
...blah blah ...
Code:
ListRef list = newList();
NodeRef node;
int i = 0;
for (i = 0; i < n; i += 1) {
node = malloc(sizeof (Node));
node->value = i + 1;
insertAfterLast(list, &node);
}
and here is the code that is a part of my linked list:
Code:
typedef struct Node {
void *data;
struct Node* next;
struct Node* prev;
} Node;
typedef Node* NodeRef;
typedef struct List {
NodeRef front;
NodeRef current;
NodeRef back;
int length;
} List;
void insertAfterLast(ListRef L, void *data) {
if (L == NULL) {
printf("List Error: calling insertAfterLast on Null ListRef");
exit(1);
}
NodeRef N;
N = malloc(sizeof (Node));
N->data = data;
N->next = NULL;
N->prev = L->back;
if (isEmpty(L)) {
L->front = N;
} else {
L->back->next = N;
}
L->back = N;
L->length += 1;
};
Both the linked list code, and the first part of my code are in their own files and have their own header files etc etc..
What is weird is that this works except that all the entries in my list have a value of n+1. (For instance, if n = 7 then every element in my linked list has a value of 7). It seems like every element of my list is referencing the same address. I'm wondering if anyone can explain why this is happening.
Please let me know if you need to see more code.