TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: George White
from: William McBrine
date: 1998-11-01 04:32:42
subject: Re: character arrays tha

-=> George White wrote to William McBrine <=-

 DC> static char *books[30] = {"moby dick", "annie", etc};

 WM> That's an array of pointers to constant strings.

 GW> Not so :-(. There is no "const" in there...

No, but it's implicit. See below...

 GW> That is an initialised array of strings of varying length that retains
 GW> its value between calls to the function it's declared in.

Not quite; it's an initialized array of *pointers to* strings, etc.
Contrast this with something like "static char books[30][10]", which would
be an array of strings.

In this case, the strings themselves -- "moby dick" and
"annie" -- are
constant strings. Their *addresses* are initially stored in books[]. You
can change, say, books[0] to point to another string; but you can't change
the strings themselves.

Consider this program:

#include 

static char *names[3] = {"foo", "bar", "baz"};

main()
{
        puts(names[0]);             /* Print "foo" */
        fgets(names[0], 3, stdin);  /* Attempt to overwrite "foo" */
        puts(names[0]);             /* Never reached, on my system */
}

Now, what happens when you hit fgets()? On my system, I get a segfault,
because it's attempting to write to a read-only area of memory. That's
because "foo", "bar" and "baz" were
considered constants, and so placed
into a read-only segment by the compiler.

On some implementations, on some systems, you WILL be able to get away
with modifying the strings; but I wouldn't want to depend on it. :-)

... William McBrine * wmcbrine{at}clark.net * http://www.clark.net/~wmcbrine/
--- MultiMail/Linux v0.20
* Origin: COMM Port OS/2 juge.com 204.89.247.1 (281) 980-9671 (1:106/2000)
SEEN-BY: 396/1 632/0 371 633/260 267 270 371 634/397 635/506 728 639/252
SEEN-BY: 670/218
@PATH: 106/2000 396/1 633/260 635/506 728 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.