This is a silly question. I have been working with pointers for almost two quarters and this question never occurred to me until today when I wrote up some code and my IDE screamed at me about it. Oddly enough, 99% of the time I get it right so this never came to me.

I'll give some examples from some of my older codes

So why when I declare a variable such as

Day *days;

, I do not need to use the -> operator and I can do this

days[pos].read();

.


However, if I declare a variable like

Appointment *appts[8];

I need to use the -> operator, so it needs to look something like

appts[apptCount++]->read();

Since they're both pointers array, don't I need to derefence so the -> operator should be necessary on the first case?

More examples:

//declaration
CGraph* m_roadMap;
m_roadMap = new CGraph(n);
//implementation
m_roadMap->AddEdge(start, end, weight);
//declaration
CGraphNode * m_verts;
m_verts = new CGraphNode[initSize];
//implementation
m_verts[i].m_dist = INFINITY;

Please advise. Thanks

>> don't I need to derefence

Yes you do

>>so the -> operator should be necessary on the first case

Nope. The operator[] deferences the pointer.

The problem is that the statement "both pointers array" is incorrect !
Appointment *appts[8]; is a pointers array
WHILE
Day * days; can be looked at as a POINTER TO AN ARRAY, array of actual Day objects, not pointers !

The problem is that the statement "both pointers array" is incorrect !
Appointment *appts[8]; is a pointers array
WHILE
Day * days; can be looked at as a POINTER TO AN ARRAY, array of actual Day objects, not pointers !

As a side note, this is one of the reasons why I like to put the asterisk next to the type name. When you write

Appointment* appts[8]

it's clearer that what you're creating is an array of pointers, not a pointer to an array.

This article has been dead for over six months. Start a new discussion instead.