Is this ok??

Dan Bernstein brnstnd at kramden.acf.nyu.edu
Sun Mar 10 07:07:47 AEST 1991


In article <1991Mar09.092611.24821 at pilikia.pegasus.com> art at pilikia.pegasus.com (Art Neilson) writes:
> I still don't think it's OK to assign the quoted string "Hello\n"
> to *s in fm2() as shown below.  Where does *s point to ?  Where in storage
> would "Hello\n" reside ?  Does the compiler assign some scratch storage or 
> something for it ??
  [ void fm2(s) char **s; { *s = "Hello\n"; } ]

"Hello\n" is a constant string. When the compiler sees it, it makes room
for it somewhere, and replaces "Hello\n" by a pointer to that location.
Under UNIX, for example, the string is either stored along with the
unwritable process text, or in the initialized data region, depending on
your compiler.

Now the string "Hello\n" has value <pointer to char,0x3753> if 0x3753 is
the location where the compiler put "Hello\n". In fm2, s has type
<pointer to pointer to char>. More precisely, say s has value
<pointer to pointer to char,0x87654>. This means that at location
0x87654 there's a <pointer to char>, say <pointer to char,0x14702>.

The assignment *s = "Hello\n" means ``Take s's value (a location in
memory), and store a pointer to "Hello\n" in that location.'' In this
case, that means to store <pointer to char,0x3753> at the location
<object,pointer to char,0x87654>. The old value of *s, namely 0x14702,
is replaced by a pointer to "Hello\n", namely 0x3753.

So the string "Hello\n" is never copied. ``*s'' refers to a
pointer-to-char object, and ``"Hello\n"'' has a pointer-to-char value.
The assignment just stores the value inside the object.

Chris will undoubtedly give a more comprehensible explanation.

---Dan



More information about the Comp.lang.c mailing list