home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!sol.ctr.columbia.edu!eff!world!ksr!jfw
- From: jfw@ksr.com (John F. Woods)
- Newsgroups: comp.lang.c
- Subject: Re: pointer explanation
- Message-ID: <18275@ksr.com>
- Date: 6 Nov 92 13:57:43 EST
- References: <895@bdrc.bdrc.bd.com>
- Sender: news@ksr.com
- Lines: 54
-
- jcl@bdrc.bd.com (John C. Lusth) writes:
- >I am teaching an introductory course in C. One of my students,
- >working on a programming assignment, posed me a question.
- > Why would the following lines of code generate an error message
- > that states "value has no members"
- > " if((strcmp (*records[min].last, *records[j].last)) > 0) "
- > OR
- > " if((strcmp (records[min].last, records[j].last)) > 0) "
- > where records is a struct entry **.
-
- >The answer I gave was...
- > Given
- > struct entry **records;
- > then
- > *records[i].last
- > is wrong because * binds tighter than [], so the above is really
- > (*records)[i].last
-
- This part of the explanation is *false*. [] binds more tightly than *,
- as does ".", so these the expression is equivalent to
-
- *(records[i].last)
-
- which is incorrect for the reasons you gave later (records[i] is a pointer
- not a structure).
-
- Rather than explaining why the statements were wrong, try encouraging reasoning
- about what would be correct:
-
- What the student wants to do is take the i'th pointer from the records array
- and dereference it to obtain a structure. So, take the i'th pointer from the
- records array:
-
- records[i]
-
- derefence it
-
- *records[i]
-
- and you have a structure, which you can then select an element of:
-
- (*records[i]).last
-
- Note the parenthesization to get the operators evaluated in the desired order;
- practice will eventually ingrain the precedence table.
-
- In C, this would be idiomatically expressed as
-
- records[i]->last
-
- which I think is much clearer, since it doesn't require parenthesization to
- get right, and is easier to explain: the pointer is records[i], and it points
- to something with a "last" element.
-
-