简体   繁体   中英

How to write to a void pointer without knowing the Data Type?

I am trying to write the code for a generic Stack using Singly Linked List in C. I am trying to use (void *) as the data type in each of its functions like:

node* getNode(void *, size_t);

void append(node **, size_t); etc.

The structure for each node is:

typedef struct linked_list{
void *data;
struct linked_list *next; }node;

In the getNode function mentioned above I am trying to do this:

node* getNode(void *data, size_t data_size) {
   node *newNode;
   newNode = (node *)malloc(sizeof(node));
   newNode->next = NULL;
  // this line should assign the void *data to the data part of the node
   return newNode;}

I could not find how to assign the data part without knowing the data type, but only using the data_size variable. I found out about the memcopy function, but even that requires the data type.

Please help.

If you only want to save a pointer to the data, you can just copy the pointer:

newNode->data = data;

If you want to copy what it points to, you need malloc to get the memory and memcpy to copy the bytes:

newNode->data = malloc(data_size);
memcpy(newNode->data, data, data_size);

The signature of memcpy is:

void *memcpy(void *dest, const void *src, size_t n);

It's meant to copy generic memory, so you can pass it a void * for both the source and destination.

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