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

Recommended Answers

All 5 Replies

>> 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.

Then how come appts[apptCount++]->read(); works? =/

Because you essentially, creating a pointer of pointers. So that means you need
to deference it 2 times.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.