Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10 5/3/83; site bbncca.ARPA Path: utzoo!watmath!clyde!burl!ulysses!mhuxr!ihnp4!bbncca!keesan From: keesan@bbncca.ARPA (Morris M. Keesan) Newsgroups: net.lang.c Subject: Re: C declarations Message-ID: <1293@bbncca.ARPA> Date: Tue, 29-Jan-85 11:31:48 EST Article-I.D.: bbncca.1293 Posted: Tue Jan 29 11:31:48 1985 Date-Received: Wed, 30-Jan-85 07:04:38 EST References: <7699@brl-tgr.ARPA> Organization: Bolt, Beranek and Newman, Cambridge, Ma. Lines: 55 ------------------------------- >From: Fred >Subject: C declarations > I have a question about C declarations. The [] notation is equivalent >to the * notation, right? We have > int ptr[] <=> int *ptr >and > int *ptr[] <=> int **ptr > The question concerns the [] syntax, which takes on a different meaning if >data initialization occurs. For example: > int ptr[]; declares one pointer >but > int ptr[] = { 1, 2, 3 }; declares a three element int array. > Is this a desirable characteristic of C? Could someone please comment on >the precise meaning of [] in declarations. Sigh. This is something we cover in this newsgroup/list at least twice a year. [] and * are NOT the same. A few citations from the C Reference Manual (CRM), as printed in "The C Programming Language", by Kernighan & Ritchie (K&R): CRM section 8.4, K&R pp. 194-5: Now imagine a declaration T D1 where T is a type-specifier (like int, etc.) and D1 is a declarator. . . . If D1 has the form D[constant-expression] or D[] then the contained identifier has type "... array of T". [Ed. note: NOT "pointer to T".] . . . When several "array of" specifications are adjacent . . . the constant expressions . . . may be missing only for the first member of the sequence. This elision is useful when the array is external and the actual definition, which allocates storage, is given elsewhere. The first constant-expression may also be omitted when the declarator is followed by initialization. In this case the size is calculated from the number of initial elements supplied. CRM section 10.1, K&R p. 205, "External function definitions": . . . since a reference to an array . . . is taken to mean a pointer to the first element of the array, declarations of formal parameters declared "array of ..." are adjusted to read "pointer to ...". So in the examples above, the declarations declare: int *ptr[]; /* ptr is a pointer to an array of int */ int ptr[]; /* ptr is an array of int, of unspecified size */ int ptr[] = { 1, 2, 3 }; /* ptr is an array of three ints */ The ONLY time (repeat ONLY) when [] is equivalent to * is in the declaration of formal parameters to a function. E.g. f(ptr) int ptr[]; { . . . } is indeed equivalent to f(ptr) int *ptr; { . . . } In retrospect, considering the confusion this has caused through the years, I think it was probably a mistake to allow this equivalence. -- Morris M. Keesan {decvax,linus,ihnp4,wivax,wjh12,ima}!bbncca!keesan keesan @ BBN-UNIX.ARPA