General C Programming

I am writing a generic implementation of linked lists in pure C.

struct Node { void *value; struct Node *next; }; struct LinkedList { struct Node *start; struct Node *end; }; void LinkedList_new(struct LinkedList* llist) { llist->start = 0; llist->end = 0; return; } void addNode( struct LinkedList *ll, void *_value ) { if ( NULL == ll->start ) { ll->start = (struct Node *) malloc( sizeof(struct Node) ); ll->end = ll->start; } else { ll->end->next = (struct Node *) malloc( sizeof(struct Node) ); ll->end = ll->end->next; } ll->end->value = _value; return; }; 

All of this works great. My problem is when I get the print value on the screen. It seems I can not find a common implementation for printing. A.

Is there a way to determine the TYPE allocated for void * ? (And then just convert using the switch statement)

 void printFunc(int aInt) { char str[15]; sprintf(str, "%d", aInt); printf(str); } 

This is an implementation that works for int. The worst case I was thinking of was writing a different function for each TYPE. Is this really my only way when using void * ?

Is there a better way to do this?

+6
source share
1 answer

No, there is no way to figure this out from a pointer. This will require that type information be stored in a specific place in all structures at runtime, which is simply not the way C uses the machine.

A common solution for the user of the data type is to provide the print function required by the application, since the application will know the type of data stored. That is, there is usually an iteration function that takes a pointer to a function, calling a user function (which can print an item) for each item in the list.

Here's what the function might look like:

 void LinkedList_foreach(const LinkedList *start, bool (*func)(void *element, void *data), void *data); 

The above should call func() for each item in the list, passing it the item data and an additional user data pointer, which the caller can use to maintain state for traversal. The func() callback should return false to stop the iteration, true to continue.

To print an integer, assuming the integers are stored in pointers, you can:

 static bool print_int(void *element, void *data) { printf("%d\n", (int) element); return true; } 

Also, do not leave the return value of malloc() in C.

+16
source

All Articles