I'm fairly new to C (and pointers in general - I have no C++ experience) and am trying to create a linked list that I can shove any type of data in. I have to use strict ANSI C only as I want to use this list in an upcoming school project for a class that allows ANSI C only.
I've got a linked list written already that works well with one type of data (I used strings when I tested it's functionality). I've read that this might be possible using void (a type agnostic bubble sort is explained here Chapter10, and there were a couple forum posts I had dug up that I cant find now)
From my understanding the only code that would need to be modified would be code that deals directly with the insides of my "Element" struct - being the struct itself, and the functions that handle creating and destroying it. Thus I'm only going to post that code (if you do need more to help just let me know ).
Other things to mention:
-I'm planning on storing different types of structs within the list
-I have to compile using the command: gcc -Wall -Wextra -ansi -pedantic main.c -o main.exe
IN MAIN
Code:
Element *newElement;
printf("\n%d: Enter a string: ", i + 1);
gets(input);
sprintf(newElementKey, "%d", (i + 1));
newElement = CreateElement(newElementKey, input, sizeof(*input));
LINKED LIST STUCTS
Code:
typedef struct Element
{
void *data; /* Pointer to data goes here */
char *key;
} Element;
typedef struct LLNode
{
struct LLNode *next;
Element *entry;
} LLNode;
typedef struct LinkedList
{
LLNode *start;
LLNode *current;
} LinkedList;
LINKED LIST FUNCTIONS
Code:
Element* CreateElement(char *elementKey, void *elementData, size_t dataSize)
{
Element *createdElement;
size_t elementKeyLength;
createdElement = malloc(sizeof(Element));
elementKeyLength = strlen(elementKey);
createdElement->key = malloc(elementKeyLength * sizeof(char));
strcpy(createdElement->key, elementKey);
createdElement->data = malloc(dataSize); /* I likely need modifications */
createdElement->data = *elementData; /* on these lines */
return createdElement;
}
/* ... */
Element* DestroyElement(Element *target)
{
if(target != NULL)
{
/* I don't know how this will interact with a "void" pointer */
free(target->data);
free(target->key);
free(target);
target = NULL;
}
return target;
}
If I try to compile right now I get the following errors, both on the line "createdElement->data = *elementData;" :
--warning: dereferencing 'void *' pointer
--error: void value not ignored as it ought to be
If I don't dereference elementData here, when I try to print it out
Code:
/* warning on this line: char format, void arg (arg 3) */
printf("\n%s: String: %s", fetchedElement.key, fetchedElement.data)
/* warning on this line: dereferencing 'void *' pointer */
printf("\n%s: String: %s", fetchedElement.key, *fetchedElement.data)