home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / lang / c / 19375 < prev    next >
Encoding:
Text File  |  1993-01-07  |  1.4 KB  |  53 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!gatech!rpi!uwm.edu!linac!att!att!dptg!rjf
  3. From: rjf@lincroftnj.ncr.com (51351[efw]-Robert Feddeler(MT4799)T343)
  4. Subject: Re: Problem with string processing.
  5. Message-ID: <1993Jan7.184518.7377@lincroftnj.ncr.com>
  6. Organization: AT&T/NCR, Lincroft, NJ, USA
  7. References: <1993Jan3.050935.1227@news2.cis.umn.edu> <Ts3TwB1w165w@wozzle.linet.org>
  8. Distribution: usa
  9. Date: Thu, 7 Jan 1993 18:45:18 GMT
  10. Lines: 41
  11.  
  12. In article <Ts3TwB1w165w@wozzle.linet.org> alane@wozzle.linet.org (J. Alan Eldridge) writes:
  13. >oleary@staff.tc.umn.edu writes:
  14. >
  15. >> A much better version is:
  16. >>  
  17. >> void add_char_to_str(char ch, char *str)
  18. >> {
  19. >>         char tmp[2] = {0};
  20. >>  
  21. >>         *tmp = ch;
  22. >>         strcat(str, tmp);
  23. >> }
  24. >>  
  25. >
  26. >Oh, dear.
  27. >
  28. >tmp[0] has a 0 in it but tmp[1] is undefined. You are not creating
  29. >a nul-terminated string here.
  30. >
  31. >If you'd said tmp[2]={0,0}; then all would be well on that front.
  32.  
  33.  
  34. And if you wanted to write it so that the implementation
  35. "looks just like the problem", you would write:
  36.  
  37. void add_char_to_str(char ch, char *str)
  38. {
  39.     int    l;
  40.  
  41.     l = strlen(str);
  42.     str[l++] = ch;
  43.     str[l] = 0;
  44. }
  45.  
  46. Highly readable, ultimately efficient (strcat() has to do a strlen()
  47. internally), and you don't have to worry about what the compiler is
  48. going to do with the initializer on the automatic.
  49.  
  50.  
  51. bob.            | Heap big trouble in the land of plenty.
  52. Were these more than just my opinions, they would have cost a bit more.
  53.