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

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!spool.mu.edu!sgiblab!news.kpc.com!kpc!hollasch
  3. From: hollasch@kpc.com (Steve Hollasch)
  4. Subject: Re: Problem with string processing.
  5. Message-ID: <1993Jan4.022737.19792@kpc.com>
  6. Sender: usenet@kpc.com
  7. Organization: Kubota Pacific Computer, Inc.
  8. References: <1993Jan2.233446.20833@iitmax.iit.edu>
  9. Distribution: usa
  10. Date: Mon, 4 Jan 1993 02:27:37 GMT
  11. Lines: 50
  12.  
  13. matujos@elof.iit.edu (Joe Matusiewicz) writes:
  14. |    I need a function to append a character to the end of a string.
  15. | I can't find an ANSI function to do so, so I tried to write my own.
  16. | Here's what I have:
  17. |          void add_char_to_str(char ch, char *str)
  18. |          {
  19. |              char *tmp;
  20. |              tmp = (char *) calloc (2*sizeof(char));
  21. |              *tmp = ch;
  22. |              *(tmp+1) = '\0';
  23. |              strcat(str, tmp);
  24. |              free (tmp);
  25. |          }
  26.  
  27.     calloc() takes two parameters:  number of elements, and element size.
  28. You should be using malloc here.  Also, you have a lot of overhead for such
  29. a simple operation.  Here's how I'd do it.
  30.  
  31.         void add_char_to_str (
  32.             register char  ch,     /* Character to Append */
  33.             register char *str)    /* Old String */
  34.         {
  35.             while (*str) ++str;
  36.             str[0] = ch;
  37.             str[1] = 0;
  38.         }
  39.  
  40.     This assumes that the space pointed to by 'str' has room for another
  41. character.  A more forgiving routine would be:
  42.  
  43.         char *add_char_to_str (
  44.             char  ch,     /* Character to Append */
  45.             char *str)    /* Old String */
  46.         {
  47.             register char *ptr;         /* New String */
  48.  
  49.             if (!(ptr = malloc (strlen(str) + 2))) return 0;
  50.  
  51.             while (*ptr++ = *str++);    /* Note assign op and null body. */
  52.             ptr[-1] = ch;
  53.             ptr[ 0] = 0;
  54.  
  55.             return ptr;
  56.         }
  57.  
  58. ______________________________________________________________________________
  59. Steve Hollasch                                   Kubota Pacific Computer, Inc.
  60. hollasch@kpc.com                                 Santa Clara, California
  61.