WLOG, assume structName is a struct with a single int member.
If I dynamically allocate for a single struct, e.g.
structName * pt = new structName;
then I can dereference the members of name as
pt->member = 10;
But if I dynamically allocate an array of structs, e.g.
structName * ps = new structName[3];
then in order to dereference a member of the i-th struct, I must write
ps[i].member = 10;
Short EXAMPLE code
----------------------------------------------------------------
int main()
{
// array case
student * pt = new student[3];
pt[1].age = 38;
cout << pt[1].age << endl;
delete [] pt;
// single struct case
student *ps = new student;
ps->age = 50;
cout << ps->age << endl;
delete ps;
return 0;
}
----------------------------------------------------------------------
Since pt and ps are both pointers, I do not understand why
pt[i]->member = 10;
is incorrect. This seems inconsistent. I can not find a reference to this issue in my textbooks or on the web. I know what is correct, i.e., pt[i].member = 10;
What I want to know is WHY or a reference which provides an explanation. Thanks in advance!
I had found empirically that [] does the dereferencing. Is this a feature particular to C++ struct arrays? I am puzzled that none of my textbooks (Prata, Lafore, Savitch) discuss such a fundamental point, i.e., why pointer[i] ==*(pointer+i), since it is not "intuitively obvious" to me. I found one article in the C++ forum that asserts that [] does the dereferencing, but does not explain why.
For example, I would have thought it equally plausible that pointer[i] is a pointer referring to the i-th struct and not the value of the i-th struct itself - but that apparently is not true. I guess what I am asking is this:
Is pointer[i] ==*(pointer+i) logically compelling or is it simply a C++ shortcut notation?