-7

I would like to create a linked list.

For the following code:

struct sampleStruct
{
    int a;
    sampleStruct *next = NULL;
};
sampleStruct *sample = new sampleStruct;

What is the difference between sample.next and sample->next?

trincot
  • 317,000
  • 35
  • 244
  • 286
redcap
  • 53
  • 10

2 Answers2

2

Okay to explain it in a more complete way. The most other guys had already wrote that you have to use '->' when ever you have a pointer. But you could also do this with '.', to do this you must respect the priority of the operators. We need the '*' to get the content of the pointer, but this has a lower priority than the '.', so you must write it into brackets to give it a higher priority, so when you want to do this with a '.' you have to wrote:

(*sample).next

and you see this is a complex syntax, to do this in a more easy way the '->' was introduced. With it you could write code in a more comfortable way.

So this is is equal to the example and it looks much better.

sample->next
Fab
  • 36
  • 7
1

Since sample is a pointer, there can't be any way to access a data member through . rather than the indirection operator ->. For example, this won't compile:

sample.next; // error: member reference type 'sampleStruct *' is a pointer;
             //        maybe you meant to use '->'?

The error actually speaks for itself.

David G
  • 94,763
  • 41
  • 167
  • 253