home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!sdd.hp.com!spool.mu.edu!umn.edu!staff.tc.umn.edu!oleary
- From: oleary@staff.tc.umn.edu ()
- Subject: Re: Problem with string processing.
- Message-ID: <1993Jan3.050935.1227@news2.cis.umn.edu>
- Sender: news@news2.cis.umn.edu (Usenet News Administration)
- Nntp-Posting-Host: staff.tc.umn.edu
- Organization: University of Minnesota
- References: <1993Jan2.233446.20833@iitmax.iit.edu>
- Date: Sun, 3 Jan 1993 05:09:35 GMT
- Lines: 50
-
-
- In article <1993Jan2.233446.20833@iitmax.iit.edu> matujos@elof.iit.edu
- (Joe Matusiewicz) writes, among other things:
-
- > void add_char_to_str(char ch, char *str)
- > {
- >1. char *tmp;
- >2. tmp = (char *) calloc (2*sizeof(char));
- >3. *tmp = ch;
- >4. *(tmp+1) = '\0';
- >5. strcat(str, tmp);
- > free (tmp);
- > }
-
- If the size of str is not big enough to handle the appended character, you're
- looking at trouble. I'll assume it is (If I'm wrong, then your code *really*
- doesn't do what you want it to).
-
- First, your call to calloc is wrong (I'm really surprised your compiler didn't
- catch this). Get yourself a good C reference, like Kernighan and Ritchie's
- "The C Programming Language."
-
- Second, you don't need to mess with dynamic memory allocation to do what you
- want.
-
- Third, learn a consistent programming style (e.g., decide on a standard
- spacing for function calls).
-
- A much better version is:
-
- void add_char_to_str(char ch, char *str)
- {
- char tmp[2] = {0};
-
- *tmp = ch;
- strcat(str, tmp);
- }
-
- You may even want to make tmp a static. You could also change the name of
- the function to make it consistent with the standard string functions,
- perhaps strcharcat(char *str, char ch)
-
-
- +-------------------> Signature Block : Version 4.1 <---------------------+
- | |
- | "The two most powerful warriors are patience and time." |
- | --- Leo Tolstoy |
- | |
- +----------------> Copyright (c) 1993 by Doc O'Leary <------------------+
-
-