Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!rutgers!sri-spam!ames!oliveb!intelca!mipos3!pinkas From: pinkas@mipos3.UUCP Newsgroups: comp.lang.c Subject: Re: Auto variable with sizeof == 0 Message-ID: <397@mipos3.UUCP> Date: Mon, 2-Feb-87 11:51:56 EST Article-I.D.: mipos3.397 Posted: Mon Feb 2 11:51:56 1987 Date-Received: Tue, 3-Feb-87 22:17:21 EST References: <4114@brl-adm.ARPA> Reply-To: pinkas@mipos3.UUCP (Israel Pinkas) Organization: Intel, Santa Clara, CA Lines: 46 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?" > >So I wrote a program that contained a similar declaration, and then tried to >take sizeof( bar ). Sure enough: > > warning: sizeof returns 0 > >[This from the VAX 11/750 4.2BSD compiler] > >Okay, that makes sense. My question is: is there any reason why you should >be able to declare an array with zero elements as an automatic variable? >What's strange is that, on the VAX, the program apparently successfully >dereferenced bar, both setting a value for "*bar" and then using that value >later. How can this be right? How can "bar" have any value at all, much >less "*bar"? If there is no use for a zero-sized automatic variable, how >come the compiler lets you do it? 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) which would allocate 100 elements to the array bar, making it the equivalent of the auto declaration struct foo **bar[100]. -Israel -- ---------------------------------------------------------------------- UUCP: {amdcad,decwrl,hplabs,oliveb,pur-ee,qantel}!intelca!mipos3!pinkas ARPA: pinkas%mipos3.intel.com@relay.cs.net CSNET: pinkas%mipos3.intel.com