httpd-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Alexei Kosut <ako...@leland.Stanford.EDU>
Subject Re: [Fwd: Problem 2534]
Date Mon, 03 Aug 1998 23:35:42 GMT
On Mon, 3 Aug 1998, David D'Antonio wrote:

> Its been a while and things might have changed, but I always thought that
> (single dimensional) arrays and pointers *are* the same thing in C, which
> is why they act the same. the square brackets are an operator which does
> pointer math and de-references the result.

Yes. In some cases, arrays and pointers are the treated very much the
same. For example, the [] operator means much the same thing for both; 
a[b] == *(a + b), regardless of what a and b are. However, the [] operator
is not the only thing one does with arrays and pointers.

Arrays and pointers are laid out differently in memory, on the stack or in
the global data area. Pointers are a couple of bytes (four or eight) that
point to an address somewhere else. Arrays allocate enough space directly
for each of the elements. This has an important meaning when you refer to
the variables by name. For example: 

char *foo;
char bar[8];

If I refer to foo, then that is just the value of foo. However, if I refer
to bar, what that really means is &bar[0], i.e., the address of the first
element of bar. In the case we're discussing, the initialization of
strings, it gets even more distinct:

char *foo = "Hello, world";
char bar[] = "Hello, world";

In both cases, thirteen characters get allocated somewhere. Both foo[2]
and bar[2] are equal to 'l'. However, the string associated with foo is
somewhere off in magic land, and all foo is is a pointer to it. OTOH, the
string associated with bar is sitting right in the stack/global area. In
fact, if you say

char foo[] = "Hello, world";
char bar[] = "Hello, world";

You get two copies of the string, because twenty-six bytes are allocated
and filled by copying the string into them. So foo != bar. On the other
hand,

char *foo = "Hello, world";
char *bar = "Hello, world";

simply allocates eight bytes (two words), and points them to the strings.
The compiler is allowed to notice that the strings are equal and make them
the same pointer. So it is possible that foo == bar. Although, as Dean
correctly pointed out, &foo != &bar, for the same reason foo != bar in the
array version.

Anyhow, that's the basic gist of it. Any good C book should explain this
much better than I do, and will probably have nice diagrams to go along
with it.

-- Alexei Kosut <akosut@stanford.edu> <http://www.stanford.edu/~akosut/>
   Stanford University, Class of 2001 * Apache <http://www.apache.org> *




Mime
View raw message