home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!spool.mu.edu!sgiblab!news.kpc.com!kpc!hollasch
- From: hollasch@kpc.com (Steve Hollasch)
- Subject: Re: Problem with string processing.
- Message-ID: <1993Jan4.022737.19792@kpc.com>
- Sender: usenet@kpc.com
- Organization: Kubota Pacific Computer, Inc.
- References: <1993Jan2.233446.20833@iitmax.iit.edu>
- Distribution: usa
- Date: Mon, 4 Jan 1993 02:27:37 GMT
- Lines: 50
-
- matujos@elof.iit.edu (Joe Matusiewicz) writes:
- |
- | I need a function to append a character to the end of a string.
- | I can't find an ANSI function to do so, so I tried to write my own.
- | Here's what I have:
- |
- | void add_char_to_str(char ch, char *str)
- | {
- | char *tmp;
- | tmp = (char *) calloc (2*sizeof(char));
- | *tmp = ch;
- | *(tmp+1) = '\0';
- | strcat(str, tmp);
- | free (tmp);
- | }
-
- calloc() takes two parameters: number of elements, and element size.
- You should be using malloc here. Also, you have a lot of overhead for such
- a simple operation. Here's how I'd do it.
-
- void add_char_to_str (
- register char ch, /* Character to Append */
- register char *str) /* Old String */
- {
- while (*str) ++str;
- str[0] = ch;
- str[1] = 0;
- }
-
- This assumes that the space pointed to by 'str' has room for another
- character. A more forgiving routine would be:
-
- char *add_char_to_str (
- char ch, /* Character to Append */
- char *str) /* Old String */
- {
- register char *ptr; /* New String */
-
- if (!(ptr = malloc (strlen(str) + 2))) return 0;
-
- while (*ptr++ = *str++); /* Note assign op and null body. */
- ptr[-1] = ch;
- ptr[ 0] = 0;
-
- return ptr;
- }
-
- ______________________________________________________________________________
- Steve Hollasch Kubota Pacific Computer, Inc.
- hollasch@kpc.com Santa Clara, California
-