Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!bloom-beacon!oberon!nunki.usc.edu!jeenglis From: jeenglis@nunki.usc.edu (Joe English) Newsgroups: comp.lang.c Subject: Re: modification of strings Keywords: string, constants, pointers Message-ID: <2606@nunki.usc.edu> Date: 6 Feb 89 05:26:04 GMT References: <345@lakesys.UUCP> Reply-To: jeenglis@nunki.usc.edu (Joe English) Distribution: usa Organization: University of Southern California, Los Angeles, CA Lines: 52 chad@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@nunki.usc.edu