C question -- pointer to array of characters

Lloyd Kremer kremer at cs.odu.edu
Thu Oct 19 00:47:39 AEST 1989


In article <6569 at ficc.uu.net> kunkee at ficc.uu.net (randy kunkee XNX MGR) writes:

>consider the declaration:
>
>	char (*foo)[];
>
>main()
>{
>	char (*foo)[];
>	char bar[20];
>
>	foo = bar;
>}
>
>Is my C compiler broken?

No, your C is broken.  :-)

In this usage

	char (*foo)[];

is equivalent to

	char (*foo)[0];

i.e. a pointer to an array of zero characters -- a pointer to a zero-sized
object.  Zero-sized objects do not really exist in C, and trying to use
them will put you on thin ice.  Incrementing a pointer to a zero-sized object
leaves it pointing to the same place (assuming the compiler recognizes it at
all), so it is not a very useful pointer.

Another problem is that you need a fairly recent (pseudo-ANSI) compiler to
take the address of an array in the way you want.  Older compilers will
complain "warning: & operator on array or function: ignored", and give you
a pointer to the first element of the array instead of to the array as a
whole.  Since the start of the array is coincident with the start of its
first element, this behavior can be circumvented using a cast.

Try the following:

	char (*foo)[20];  /* pointer to an array of 20 characters */
	char bar[20];     /* array of 20 characters */

#ifdef __STDC__
	foo = &bar;
#else
	foo = (char (*)[20])bar;
#endif

-- 
					Lloyd Kremer
					...!uunet!xanth!kremer
					Have terminal...will hack!



More information about the Comp.lang.c mailing list