String help!

Joseph S. D. Yao jsdy at hadron.UUCP
Thu Mar 14 00:45:43 AEST 1985


> >> Is it allowed & portable to use the construct:
> >> char* foo(){
> >> return("foobar");    
> >> }
> >> This would hopefully return a pointer to the string "foobar"..
> >Yes it does....However it is a pointer to a STATIC data area.
> >So it wouldn't be a good idea to change the contents of the string.
> David Herron is right, except for the fact that you are allowed to
> change the contents of the string as long as you don't change the 
> length of it!

Perhaps you should remember that if you do, say, strcpy(foo(), "barfoo")),
then the next call to foo() will return "barfoo".  This is because the
"barfoo" string is copied into the static location of the string that
is returned by foo().  Another way to say this is that new instances
of the string "foobar" are  n o t  dynamically created each time you
call foo().  All of this assumes, BTW, that you are not using a DEC or
ANSI C compiler.

Also BTW, one response asks about the legitimacy of not being able to
modify the contents of any valid pointer.  In case henry's answer didn't
suggest it, ANSI C introduces a new storage class "const", which is a
class of data which may be assumed to remain constant, and (i guess if
possible) should be placed in read-only storage.  A no-write data-space
psect fills this requirement.  The opposite is "volatile", which means:
"Even if you are optimising the heck out of this code, watch it!  This
variable will change when you least expect it!"  This is good for data
manipulated by interrupt routines, or if you feel like being perverse
while adb/sdb/dbx'ing the thing.	;-)

Joe Yao		hadron!jsdy at seismo.{ARPA,UUCP}

*BTW == By The Way, for our friends not in the States.	;-)



More information about the Comp.lang.c mailing list