3

Possible Duplicate:
What can I use instead of the arrow operator, ->?
What does -> mean in C++?

So I'm currently studying for a C++ exam about Data Structure and Algorithm Development. While looking though my teacher powerpoints, I've noticed that he's used this "->" a lot. And I'm not sure what it means? Is it really a command you can do in c++?

Example 1

addrInfo *ptr = head;
while (ptr->next != NULL) 
{
        ptr = ptr->next;
}   
// at this point, ptr points to the last item

Example 2

if( head == NULL )
{
head = block;
block->next = NULL;
}
Community
  • 1
  • 1
Robolisk
  • 1,561
  • 4
  • 18
  • 39
  • Just an additional comment, the `->` operator is called the 'pointer to member' operator. I'm not sure why so many people don't have a name for it. – Collin Dauphinee Mar 07 '12 at 03:38

5 Answers5

8

It is a combination dereference and member-access. This ptr->next is equivalent to (*ptr).next.

Gordon Bailey
  • 3,803
  • 19
  • 28
5

The -> operator deferences a pointer and retrieves from it the memory index beyond that point indicated by the following name. Thus:

struct foo {
   int bar;
   int baz;
};

struct foo something;
struct foo *ptr = &something;

ptr->bar = 5;
ptr->baz = 10;

In the above, the ptr value will be the memory location of the something structure (that's what the & does: finds the memory location of something). Then the ptr variable is later "dereferenced" by the -> operator so that the ptr->bar memory location (an int) is set to 5 and ptr->baz is set to 10.

Wes Hardaker
  • 20,929
  • 2
  • 37
  • 68
1

It's de-referencing the pointer. It means "Give me the value of the thing pointed at the address stored at ptr". In this example, ptr is pointing to a list item so ptr->next returns the value of the object's next property.

D Stanley
  • 144,385
  • 11
  • 166
  • 231
1

The -> operator is specifically a structure dereference. In block->next it is calling the member variable next of the object which the pointer block points to. See this page for a list of member and pointer operators in C++.

Basically, it's doing the same thing as block.next, were block an object rather than a pointer.

rob05c
  • 1,183
  • 1
  • 8
  • 18
1

-> is an operator of pointer. It is used for pointer to access member.

If you take a look at the defination of "addrInfo", you can find the member "next".

Otherwise, you can see the following example:

struct student
{
int num;
}
struct student stu;
struct student *p;
p=&stu;

These three operations are equal: 1. stu.num 2. (*P).num 3. p->num

Timothy Ye
  • 25
  • 3