简体   繁体   中英

How to create an array of pointers to structs? C++

I wrote this piece of code that I am not sure exactly how it works, but it works. This is the code:

  struct node
{
    string data;
    node *chain;
};

   int tablesize=10;

  node *ptr [tablesize];

  for (i=0; i<tablesize; i++)
{
    ptr[i]=new node;
    ptr[i]->data="Empty";
    ptr[i]->chain=NULL;
}

If I understand it correctly, first I create an array of 10 pointers, then I assign each pointer with a new node? Why does it work only when I dereference it twice though? ( ptr[i]->data="Empty";)

Because ptr is declared as an array of pointers. Thus ptr[i] is a pointer to node. Hence you need to dereference it in order to access the pointed to entitiy.

ptr[i] is a node* therefore you have to use ->

(you are not de-referencing)

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