mixing pointers and arrays

Tom Beres tom at rlgvax.UUCP
Sat Aug 6 08:34:45 AEST 1983

If you realize that "char *p;" and "char p[];" are different and you
don't need an explanation why, skip this.  If not, read on.
NEAL WYSE at ihuxp, I think you need to read this.

Just because you can interchange "char *p;" and "char p[];" when
declaring a formal parameter does NOT mean you can confuse these
2 everywhere else.  They are NOT the same!

char foo[10];
foo[1] = '\0';
	means:  Take the ADDRESS "foo" and add 1 to it to get a new address.
	Then put a '\0' in the memory location indicated by that address.

char *foo;
foo[1] = '\0';
	means:  Look at the ADDRESS "foo" and take the VALUE you find in
	there.  Add 1 to that VALUE.  Now use that VALUE as an address,
	and put a '\0' in the memory location indicated by that address.
	NOTE: I realize that "foo" should first be set to point to someplace

In both cases you can use indexing (i.e. "xxx[yyy]" is legit) but DIFFERENT
things happen in both cases!  In order for the compiler to generate the
right code, it must know whether "foo" is an array or a pointer.  In:

file 1:			|	file 2:
char array[10];		|	extern char *array;

You are giving the wrong information to the compiler in File 2.  The compiler
will oblige by giving you back wrong code.  You are stating in File 2 that
"array" is the address of a character pointer, so the code produced will
fit the 2nd description above.  But File 1 says that "array" is the
address of the first of 10 sequentially stored characters, so File 1
will produce code to suit the first description above.

Now for the question 'why can you use "char foo[];" and "char *foo;"
interchangably when declaring a formal parameter to a subroutine?'.
The reason is that, as we all know, when you pass an array in C, what
really gets passed to the subroutine is the address of the first element,
and the parameter variable will be initialized to that address.  So, the
parameter is really an honest-to-goodness pointer variable.  C knows that,
too, and what's more is a bit lenient about it.  If you declare the parameter
as "char foo[];" the compiler recognizes that the whole array really won't
be passed, that only the address will be, and that the parameter needs to be
a pointer, so C correctly interprets the slightly misstated declaration.

This leniency of interpretation is provided only when declaring parameters,
nowhere else!

- Tom Beres
{seismo, allegra, brl-bmd, mcnc, we13}!rlgvax!tom

More information about the Comp.lang.c mailing list