简体   繁体   中英

Printing elements of a linked list containing void*

I'm implementing a generic doubly linked list in C, and I've written functions for forward and backward traversal. Within these functions, I'd like to print the data contained in the list, but since it's generic, I'm having a hard time figuring out how this can be done. Obviously I can't just printf using %d or something because the list could contain any data type. Any suggestions to approach this differently would be appreciated because I've been thinking about it for quite some time and I'm at a loss. Thanks!

You can do a lot of things.

For example, you can store structs that not only contain a void * to your element's data, but also an indication for the possible data type, or even just the format string necessary to printf the object.

You could also think of a struct that contains a void * to your data, and a function pointer that will allow you to convert your data to a string. That is basically minimally emulating C++'s polymorphism in C.

EDIT: as wickstopher pointed out, you just don't get compile-time type safety with this. Mess up the function pointer, and you'll have an unsuitable function working on your data, possibly causing your program to segfault, run over your kitten, burn down your apartment, run away with your youngest child or smoke crack in your kitchen.

You need a tag field in the struct you declared for node. Define an enum for data types as

enum {INT_TYPE, FLOAT_TYPE, DOUBLE_TYPE, CHAR_TYPE} type;

For every data type you need to assign type with corresponding enumeration constant. In printing function you will have to check the value of type and then use the appropriate specifier.

C does not support any sort of runtime type checking, so this is not possible. See runtime determine type for C (similar question).

If you want to support a limited range of data types, you might consider an adding an enum to your node structure, but this won't get you true generic functionality and won't be enforceable at compile time.

Assuming your node has a void * pointer to node contents, among pointers for referring the next and previous elements in the list, provide a function to print a node, such as

void PrintNode (Node_t *node, void (*fprint)(void *));

This function will get the elements of a node, and then call a user-provided function to actually print the contents of a node.

typedef struct stNode {
  void *NodeContents;
  struct stNode *prev;
  struct stNode *next;
} Node_t;

void PrintNode (Node_t *node, void (*print)(void *))
{
  if (node && node->NodeContents && print)
    print(node->NodeContents);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM