-1

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.

FlarrowVerse
  • 197
  • 2
  • 13

1 Answers1

3

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.

dbush
  • 205,898
  • 23
  • 218
  • 273