throopw@rtp47.UUCP (Wayne Throop) (09/10/85)
> I'm disgusted at the number of 'wizards' who are confused. > 'x' should best be though of as a pointer to array of two ints. > int y[2][2][2]; /* y should best be thought of as a pointer to > two dimentional array of ints ([2][2]) */ > int yp[][2][2] = y; /* is a proper pointer */ > Jeff Anton ucbvax!anton anton@BERKELEY.EDU Now wait a minuite. As near as I can tell from this fragment, Jeff is as confused as any other wizard. Since an initializer is used in the declaration int yp[][2][2] = y; yp is clearly *not* a formal. And this being the case, *yp* *is* *not* (I repeat *not*) a pointer. I assume what is meant to happen for the two above declarations is int y[2][2][2]; int (*yp)[2][2] = y; The abomination Jeff gave above declares yp to be an array of 1 array of 2 array of 2 integers, and (if the compiler doesn't choke) initializes yp[0][0][0] to be the expression (int)y. Yuck. I tried this C file on SysV lint: int x1[2][2]; int x2[][2] = x1; /* I hope lint complains here */ int (*x3)[2] = x1; /* I hope lint doesn't complain here */ And lint quite properly complained, saying: warning: illegal combination of pointer and integer: (2) operator = It is interesting that pointer/array equivalence causes such problems, when it it really so simple. The *only* (I repeat *only*) place where a declarator like "int x[]" declares x to be a pointer is in *formal* declarations. In static, external, or automatic declarations, *x* *is* *an* *array* (of compiler or loader determined size). And even in formal declarations, x "should be" *thought of* as an array. -- Note that Followup-To specifies net.lang.c -- "People who live in glass houses, shouldn't" -- Wayne Throop at Data General, RTP, NC <the-known-world>!mcnc!rti-sel!rtp47!throopw
guy@sun.uucp (Guy Harris) (09/10/85)
> >Does anybody else think that the array/pointer semi-equivalence is probably > >one of the major causes of errors in C coding? > > I always thought the array/pointer semi-equivalence was one of the major > causes of easier to {read,understand} coding. You missed the point. The array/pointer semi-equivalence seems to be one of the major causes of *incorrect* code, as well. It's not a question of how readable the code is once it's written, it's a question of whether it'll get written correctly in the first place. Every so often, somebody asks why file1.c: extern int *foo; file2.c: int foo[42]; doesn't work. The person asking the question obviously doesn't realize that just because you can say "foo[13]" in either case doesn't mean that the two declarations mean the same thing. Another common question is "why doesn't this work?": struct frobozz *foo; get_frobozz_value(foo); which code proceeds to smash some arbitrary location pointed to by the uninitialized pointer "foo". I suspect this assumption that a pointer to a structure, absent a structure for it to point to, is just as good as a structure is fallout from pointer/array confusion. Guy Harris