modification of strings
Joe English
jeenglis at nunki.usc.edu
Mon Feb 6 15:26:04 AEST 1989
chad at lakesys.UUCP writes:
> char *blah = "meow";
> char *tmp;
>
> tmp = strcpy(blah, "grr, snarl, hiss");
>
>I would think since the string 'blah' is considered to be nonmodifiable that
>it would not be changed, but the result would be placed into tmp.
>[...]
>Apparently, either the effect of strings is not yet defined in these
>implementations, or, more likely, what I was taught is incorrect.
What you were taught is incorrect.
The type "char *" means, "pointer to char." A char *
can point to either a single character or an array
of characters (or NULL or a garbage value.) Since
strings are stored as arrays of characters, "char *"
is the type used to reference them; but you still
get pointer semantics, not string semantics as in
other languages.
The str... functions give some string manipulation
functionality, but you still have to allocate space
for the strings themselves. For example, strcat(char
*s1,char *s2) places a copy of the string pointed to
by s2 immediately after the string pointed to by s1,
where the end of each string is determined by a '\0'
character value. If s1 doesn't point to an area of
memory large enough to hold both strings, you have
problems.
Another note: the return value of strcat, strcpy,
etc., is for the most part useless. strcat(s1,s2)
returns s1 (which the caller presumably already
knows); it does *not* make a new string.
So in your example above, blah points to an array
5 characters long which is initialized to
{'m','e','o','w','\0' }. Since the array is only 5
characters long, any attempts to write data past its
end (like the call to strcat() does) is going to
cause undefined, usually harmful behaviour.
Hope this helps,
--Joe English
jeenglis at nunki.usc.edu
More information about the Comp.lang.c
mailing list