Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!rutgers!sri-spam!ames!amdahl!amdcad!tim From: tim@amdcad.UUCP Newsgroups: comp.lang.c Subject: Re: Auto variable with sizeof == 0 Message-ID: <14575@amdcad.UUCP> Date: Mon, 2-Feb-87 20:49:30 EST Article-I.D.: amdcad.14575 Posted: Mon Feb 2 20:49:30 1987 Date-Received: Tue, 3-Feb-87 22:23:28 EST References: <4114@brl-adm.ARPA> <397@mipos3.UUCP> Reply-To: tim@amdcad.UUCP (Tim Olson) Organization: Advanced Micro Devices, Sunnyvale, California Lines: 43 In article <397@mipos3.UUCP> pinkas@mipos3.UUCP (Israel Pinkas) writes: >In article <4114@brl-adm.ARPA> escott%deis.uci.edu@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