Article View: comp.std.c
Article #2971Re: idle query on strtok()
From: Norman Diamond
Date: Fri, 20 Nov 1992 01:28
Date: Fri, 20 Nov 1992 01:28
44 lines
2315 bytes
2315 bytes
In article <722063993snx@grendel.demon.co.uk> jes@grendel.demon.co.uk (Jim Segrave) writes:
>Is strtok()'s behaviour defined for tokens already taken from a string?
strtok() only steps on separators, so the tokens remain unchanged.
> char zoe[] = "aaa bbb";
> char *first, *second;
> first = strtok (zoe, " ");
> second = strtok (NULL, " ");
> printf ("%s\n%s\n", first, second);
>I expect the output:
> aaa
> bbb
Perfect example.
>Can I *portably* change the contents of a token returned by strtok
>without affecting the behaviour of subsequent calls?
> strcpy (first, "!!!"); /* corrupt the first bit */
> second = strtok (NULL, " ");
> printf ("%s\n", second);
Yes. strtok() is defined as keeping a pointer internally to the remaining
portion of the string, from which its next search will continue. The
second result will still be bbb.
>What if I change the 'corrupt ...' line to
> memset (first, 0, strlen (first) + 1);
No change. The first call to strtok() already set *(first + strlen (first))
to 0, so you're just setting it to 0 again, as well as zeroing the token.
>Does strtok() promise that the tokens delivered will be untouched
>by subsequent calls to strtok()?
Not explicitly, but still yes. Library functions are defined (ideally
anyway, since some aren't defined very clearly :-) to have certain effects
on valid arguments, and are not allowed to go stepping on other parts of
the program or have other random behavior unless you pass invalid arguments
or you have otherwise violated the conditions.
--
Norman Diamond diamond@jit081.enet.dec.com
If this were the company's opinion, I wouldn't be allowed to post it.
"It's been a lovely recession."
Technical Details
Message-ID:
<1992Nov20.012856.14506@nntpd.lkg.dec.com>Path:
arc1-ca.pugleaf.net!sparky!uunet!haven.umd.edu!decuac!pa.dec.com!nntpd2.cxo.dec.com!nntpd.lkg.dec.com!jit345.bad.jit.dec.com!diamondReferences:
<722063993snx@grendel.demon.co.uk>Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c Path: arc1-ca.pugleaf.net!sparky!uunet!haven.umd.edu!decuac!pa.dec.com!nntpd2.cxo.dec.com!nntpd.lkg.dec.com!jit345.bad.jit.dec.com!diamond From: diamond@jit345.bad.jit.dec.com (Norman Diamond) Subject: Re: idle query on strtok() Message-ID: <1992Nov20.012856.14506@nntpd.lkg.dec.com> Sender: usenet@nntpd.lkg.dec.com (USENET News System) Reply-To: diamond@jit.dec.com (Norman Diamond) Organization: Digital Equipment Corporation Japan , Tokyo References: <722063993snx@grendel.demon.co.uk> Date: Fri, 20 Nov 1992 01:28:56 GMT Lines: 44