home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / c / 16144 < prev    next >
Encoding:
Internet Message Format  |  1992-11-08  |  1.9 KB

  1. Path: sparky!uunet!zaphod.mps.ohio-state.edu!sol.ctr.columbia.edu!eff!world!ksr!jfw
  2. From: jfw@ksr.com (John F. Woods)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: pointer explanation
  5. Message-ID: <18275@ksr.com>
  6. Date: 6 Nov 92 13:57:43 EST
  7. References: <895@bdrc.bdrc.bd.com>
  8. Sender: news@ksr.com
  9. Lines: 54
  10.  
  11. jcl@bdrc.bd.com (John C. Lusth) writes:
  12. >I am teaching an introductory course in C.  One of my students,
  13. >working on a programming assignment, posed me a question.
  14. >    Why would the following lines of code generate an error message
  15. >    that states "value has no  members"
  16. >    " if((strcmp (*records[min].last, *records[j].last)) > 0) "
  17. >    OR
  18. >    " if((strcmp (records[min].last, records[j].last)) > 0) "
  19. >    where records is a struct entry **.
  20.  
  21. >The answer I gave was...
  22. >    Given
  23. >    struct entry **records;
  24. >    then
  25. >    *records[i].last
  26. >    is wrong because * binds tighter than [], so the above is really
  27. >    (*records)[i].last
  28.  
  29. This part of the explanation is *false*.  [] binds more tightly than *,
  30. as does ".", so these the expression is equivalent to
  31.  
  32.     *(records[i].last)
  33.  
  34. which is incorrect for the reasons you gave later (records[i] is a pointer
  35. not a structure).
  36.  
  37. Rather than explaining why the statements were wrong, try encouraging reasoning
  38. about what would be correct:
  39.  
  40. What the student wants to do is take the i'th pointer from the records array
  41. and dereference it to obtain a structure.  So, take the i'th pointer from the
  42. records array:
  43.  
  44.     records[i]
  45.  
  46. derefence it
  47.  
  48.     *records[i]
  49.  
  50. and you have a structure, which you can then select an element of:
  51.  
  52.     (*records[i]).last
  53.  
  54. Note the parenthesization to get the operators evaluated in the desired order;
  55. practice will eventually ingrain the precedence table.
  56.  
  57. In C, this would be idiomatically expressed as
  58.  
  59.     records[i]->last
  60.  
  61. which I think is much clearer, since it doesn't require parenthesization to
  62. get right, and is easier to explain:  the pointer is records[i], and it points
  63. to something with a "last" element.
  64.  
  65.