home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!gatech!rpi!uwm.edu!linac!att!att!dptg!rjf
- From: rjf@lincroftnj.ncr.com (51351[efw]-Robert Feddeler(MT4799)T343)
- Subject: Re: Problem with string processing.
- Message-ID: <1993Jan7.184518.7377@lincroftnj.ncr.com>
- Organization: AT&T/NCR, Lincroft, NJ, USA
- References: <1993Jan3.050935.1227@news2.cis.umn.edu> <Ts3TwB1w165w@wozzle.linet.org>
- Distribution: usa
- Date: Thu, 7 Jan 1993 18:45:18 GMT
- Lines: 41
-
- In article <Ts3TwB1w165w@wozzle.linet.org> alane@wozzle.linet.org (J. Alan Eldridge) writes:
- >oleary@staff.tc.umn.edu writes:
- >
- >> A much better version is:
- >>
- >> void add_char_to_str(char ch, char *str)
- >> {
- >> char tmp[2] = {0};
- >>
- >> *tmp = ch;
- >> strcat(str, tmp);
- >> }
- >>
- >
- >Oh, dear.
- >
- >tmp[0] has a 0 in it but tmp[1] is undefined. You are not creating
- >a nul-terminated string here.
- >
- >If you'd said tmp[2]={0,0}; then all would be well on that front.
-
-
- And if you wanted to write it so that the implementation
- "looks just like the problem", you would write:
-
- void add_char_to_str(char ch, char *str)
- {
- int l;
-
- l = strlen(str);
- str[l++] = ch;
- str[l] = 0;
- }
-
- Highly readable, ultimately efficient (strcat() has to do a strlen()
- internally), and you don't have to worry about what the compiler is
- going to do with the initializer on the automatic.
-
-
- bob. | Heap big trouble in the land of plenty.
- Were these more than just my opinions, they would have cost a bit more.
-