home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / lang / c / 19145 < prev    next >
Encoding:
Text File  |  1993-01-03  |  2.2 KB  |  63 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!zaphod.mps.ohio-state.edu!sdd.hp.com!spool.mu.edu!umn.edu!staff.tc.umn.edu!oleary
  3. From: oleary@staff.tc.umn.edu ()
  4. Subject: Re: Problem with string processing.
  5. Message-ID: <1993Jan3.050935.1227@news2.cis.umn.edu>
  6. Sender: news@news2.cis.umn.edu (Usenet News Administration)
  7. Nntp-Posting-Host: staff.tc.umn.edu
  8. Organization: University of Minnesota
  9. References: <1993Jan2.233446.20833@iitmax.iit.edu>
  10. Date: Sun, 3 Jan 1993 05:09:35 GMT
  11. Lines: 50
  12.  
  13.  
  14. In article <1993Jan2.233446.20833@iitmax.iit.edu> matujos@elof.iit.edu
  15. (Joe Matusiewicz) writes, among other things:
  16.  
  17. >         void add_char_to_str(char ch, char *str)
  18. >         {
  19. >1.           char *tmp;
  20. >2.           tmp = (char *) calloc (2*sizeof(char));
  21. >3.           *tmp = ch;
  22. >4.           *(tmp+1) = '\0';
  23. >5.           strcat(str, tmp);
  24. >             free (tmp);
  25. >         }
  26.  
  27. If the size of str is not big enough to handle the appended character, you're
  28. looking at trouble.  I'll assume it is (If I'm wrong, then your code *really*
  29. doesn't do what you want it to).
  30.  
  31. First, your call to calloc is wrong (I'm really surprised your compiler didn't
  32. catch this).  Get yourself a good C reference, like Kernighan and Ritchie's
  33. "The C Programming Language."
  34.  
  35. Second, you don't need to mess with dynamic memory allocation to do what you
  36. want.
  37.  
  38. Third, learn a consistent programming style (e.g., decide on a standard
  39. spacing for function calls).
  40.  
  41. A much better version is:
  42.  
  43. void add_char_to_str(char ch, char *str)
  44. {
  45.         char tmp[2] = {0};
  46.  
  47.         *tmp = ch;
  48.         strcat(str, tmp);
  49. }
  50.  
  51. You may even want to make tmp a static.  You could also change the name of
  52. the function to make it consistent with the standard string functions,
  53. perhaps strcharcat(char *str, char ch)
  54.  
  55.  
  56. +------------------->  Signature Block : Version 4.1  <---------------------+
  57. |                                                                           |
  58. |          "The two most powerful warriors are patience and time."          |
  59. |                                            --- Leo Tolstoy                |
  60. |                                                                           |
  61. +---------------->   Copyright (c) 1993 by Doc O'Leary   <------------------+
  62.  
  63.