Auto variable with sizeof == 0

tim at amdcad.UUCP tim at amdcad.UUCP
Tue Feb 3 11:49:30 AEST 1987


In article <397 at mipos3.UUCP> pinkas at mipos3.UUCP (Israel Pinkas) writes:
>In article <4114 at brl-adm.ARPA> escott%deis.uci.edu at icsg.uci.edu (Scott Menter) writes:
>>				... I found a construct that
>>seems a little strange to me: an automatic variable was declared as a
>>"struct foo **bar[]".  "How could this be right?"  I said to myself.  "How
>>can you declare an automatic variable that has no size?"

It isn't right!

>
>I don't see the problem with this declaration.  bar is declared to be an
>array of pointers to pointers to struct foo.  That is, **(bar[0]) is of
>type foo.  bar initially has no memory allocated to it.  This type of
>construct appears to be a dynamic array, where malloc will be called to get
>some memory.  Since the array is declared to have zero elements, sizeof
>will return zero.  (Remember that sizeof(array) =~ sizeof(element of array)
>times number of elements.  This is approximate because C allows a compiler
>to pack arrays.)  So in your case, the compiler was correct in warning you
>that bar was of size zero (taking sizeof a zero sized element is not very
>useful as the most common uses for sizeof are malloc and pointer arithmatic
>when something cast the pointer to a different type).  You should inspect
>the code, but if it worked on one machine, it should work on another.  It
>could be that they really wanted to say sizeof(foo), in something like:
>
>	bar = malloc(sizeof(struct foo) * 100)
>

	^^ Won't work; bar is a *constant* (see pp 94, 95 of K&R)

>which would allocate 100 elements to the array bar, making it the
>equivalent of the auto declaration struct foo **bar[100].

There are only 3 places where an array declaration is not required to
declare a size between the brackets []:

	1:	an extern array		-->	extern int foo[];
	2:	an initialized array	-->	int foo[] = {1,2,3};
	3:	an array parameter	-->	foo(bar)
						int bar[];


	Tim Olson
	Advanced Micro Devices



More information about the Comp.lang.c mailing list