mercredi 27 septembre 2017

Another void* topic; I just have to ask because I am confused

Ok, muddling though Stack on the particulars about void*, books like The C Programming Language (K&R) and The C++ Programming Language (Stroustrup). What have I learned? That void* is a generic pointer with no type inferred. It requires a cast to any defined type and printing void* just yields the address.

What else do I know? void* can't be dereferenced and thus far remains the one item in C/C++ from which I have discovered much written about but little understanding imparted.

I understand that it must be cast such as *(char*)void* but what makes no sense to me for a generic pointer is that I must somehow already know what type I need in order to grab a value. I'm a Java programmer; I understand generic types but this is something I struggle with.

So I wrote some code

typedef struct node
{
  void* data;
  node* link;
}Node;

typedef struct list
{
   Node* head;
}List;

Node* add_new(void* data, Node* link);

void show(Node* head);

Node* add_new(void* data, Node* link)
{
  Node* newNode = new Node();
  newNode->data = data;
  newNode->link = link;

  return newNode;
}

void show(Node* head)
{
  while (head != nullptr)
  {
      std::cout << head->data;
      head = head->link;
  }
}

int main()
{
  List list;

  list.head = nullptr;

  list.head = add_new("My Name", list.head);

  list.head = add_new("Your Name", list.head);

  list.head = add_new("Our Name", list.head);

  show(list.head);

  fgetc(stdin);

  return 0;
}

I'll handle the memory deallocation later. Assuming I have no understanding of the type stored in void*, how do I get the value out? This implies I already need to know the type, and this reveals nothing about the generic nature of void* while I follow what is here although still no understanding.

Why am I expecting void* to cooperate and the compiler to automatically cast out the type that is hidden internally in some register on the heap or stack?

Aucun commentaire:

Enregistrer un commentaire