home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / lang / c / 18650 < prev    next >
Encoding:
Internet Message Format  |  1992-12-21  |  2.1 KB

  1. Path: sparky!uunet!spool.mu.edu!umn.edu!csus.edu!netcom.com!netcomsv!ulogic!hartman
  2. From: hartman@ulogic.UUCP (Richard M. Hartman)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: pointer assignment problem
  5. Message-ID: <749@ulogic.UUCP>
  6. Date: 18 Dec 92 18:50:58 GMT
  7. References: <1992Dec13.181118.2693@seas.gwu.edu> <Bz9Gxp.DMz@netnews.jhuapl.edu>
  8. Distribution: usa
  9. Organization: negligable
  10. Lines: 60
  11.  
  12. In article <Bz9Gxp.DMz@netnews.jhuapl.edu> bandy@netnews.jhuapl.edu (Mike Bandy) writes:
  13. >saud@seas.gwu.edu (Temporary account (slc 11/19/92)) writes:
  14. >
  15. >>Hi:
  16. >
  17. >>I am having problem with pointer assignment 
  18. >
  19. >>look at this pleae
  20. >>    
  21. >>    function_node    *tmp_node;
  22. >
  23. >>    tmp_node = (function_node *) malloc (sizeof(tmp_node));
  24. >
  25. >Think about what tmp_node is; it's a pointer to a structure.  What gets
  26. >malloc'ed is (probably) 4 bytes of memory.  Stick a '*' in the sizeof
  27. >to tell it to allocate how much tmp_node _points to_ .  Like:
  28. >
  29. >    tmp_node = (function_node *) malloc (sizeof(*tmp_node));
  30.  
  31. I tend to take the other tactic.  I *never* use a variable name
  32. as the argument to sizeof() used in a malloc(), I always use the
  33. type name.  e.g.:
  34.  
  35.     tmp_node = (function_node *) malloc(sizeof(function_node));
  36.  
  37. This can even be encapsulated into a generic "give me a" macro:
  38.  
  39.     #define NEW(xxx) (xxx *) malloc(sizeof(xxx))
  40.     tmp_node = NEW(function_node);
  41.  
  42. I actually don't use the NEW macro, I just give it as an option.
  43.  
  44. The main reason I use the type is that I always know what I
  45. wanted.  If I use the variable we have the problem you have
  46. (forgetting the *) and ambiguity.
  47.  
  48.     ptr = malloc(sizeof(*ptr));
  49.  
  50. what does that tell me?
  51.  
  52.     ptr = malloc(sizeof(struct employee_rec));
  53.  
  54. tells me that ptr is supposed to hold employee information.
  55.  
  56. Of course, so should the declaration of ptr....
  57.  
  58. And, "ptr" may not be the best name....
  59.  
  60. However, I think it is safest and clearest to only use types
  61. for malloc/sizeof statements and stay away from the implicit
  62. "you figure out the type and give me one" style that using
  63. the variable names represents.
  64.  
  65.  
  66.         -Richard Hartman
  67.         hartman@ulogic.COM
  68.  
  69. =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
  70. "Who knows what evil lurks in the hearts of men?"
  71.  
  72.