2

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";)

2
  • 2
    Because ptr[i] is a pointer. You are not de-referencing twice. BTW you are using variable length arrays (VLAs), which are not standard C++. Commented Oct 30, 2013 at 8:20
  • Don't forget to clean up your mess... Commented Oct 30, 2013 at 8:26

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

So is it right to say that node *ptr [tablesize]; is actually pointer to pointer array?
@Reboot_87 no, it is an array of pointers to node. Just like int a[10] is an array of ints.
I think it is because: node *ptr [tablesize]; is the same as writing: node **ptr=new node *[tablesize];
0

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

(you are not de-referencing)

1 Comment

No? What would you call it, then?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.