C question -- pointer to array of characters

Chris Torek chris at mimsy.umd.edu
Wed Oct 18 13:41:23 AEST 1989


`char (*)[]' is an evil, nefarious type which will suck you into
a pit of despair.  (Fortunately, a fierce green snake bars the way.)

In article <6569 at ficc.uu.net> kunkee at ficc.uu.net (randy kunkee XNX MGR) writes:
>Forget that you probably wouldn't want to do the following and
>consider the declaration:
>
>	char (*foo)[];
>
>This declares "foo" to be a pointer to an array of characters.

More precisely, it declares foo as a pointer to array of unknown size of
characters.  Foo can then point to zero or more such arrays.  The problem
is that if foo points to two such arrays, there is no possible way to
find where the second such array begins.  (The first one begins where
foo points, but only because for all x \elem possible-sizes, 0*x gives 0.)

>My question is, how can you get an assignment to "foo" without
>the C compiler complaining about different levels of indirection
>(ie. make "foo" point to real storage) without using a typecast?

First you need an array of unknown size.  Then simply take its address.
The *only* correct way to declare an array of unknown size is as
an `extern':

	extern char bar[];
	f() { char (*foo)[]; foo = &bar; }

>For example:
>
>main()
>{
>	char (*foo)[];
>	char bar[20];
>
>	foo = bar;
>}

Here `bar' has type `array 20 of char'; in an rvalue context, this
changes to type `pointer to char', so a correct version of main()
would be

	int main() { char *foo; char bar[20]; foo = bar; return (0); }

In ANSI C (when and if it ever appears), `&bar' will produce a value
with type `pointer to array 20 of char', so a second correct version
of main() would be

	main() { char (*foo)[20]; char bar[20]; foo = &bar; exit(0); }

(There is no particular significance to the change from `return 0' to
`exit 0'.)
-- 
`They were supposed to be green.'
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list