Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ncar!tank!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Clarification needed on Pointers/Arrays Message-ID: <16088@mimsy.UUCP> Date: 23 Feb 89 06:11:40 GMT References: <1436@etive.ed.ac.uk> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 70 In article <1436@etive.ed.ac.uk> sam@lfcs.ed.ac.uk (S. Manoharan) writes: >I need to reason the likely outcome of > /* LINE 1 */ and /* LINE 2 */ Okay. Take a deep breath: First, we need to get rid of irrelevant stuff. So: > static char *a[] = { "123456789", "bull", "fred", "foo" }; > foo1(a); > foo2(a); The object `a' has the pair% . In each call, this is converted to the rvalue . ----- % C values are always typed. You cannot talk about a value without also talking about its type (although you can talk about a type without any particular value). This is why there is no nil pointer: there is a nil pointer-to-char, a nil pointer-to-int, and so forth, but there is no `nil pointer'. There is also no 0, just a 0 short, a 0.0 float, a 0L long, and so forth. Eliding the type is a popular way to confuse oneself. ----- >foo1(b) >char *b; >{ All bets are off. `b' does not match the actual argument's type, so its value is not describable. > printf("Entries %d\n",sizeof(b)/sizeof(char *)); sizeof(b) is the size of `char *' (since b is `char *'), so the divide produces 1. > /* LINE 1 */ for ( i = 0; i < 10; ++i ) printf("%d: %c\n",i,b+i); The result of this is (as the VAX architecture manual likes to say) UNPREDICTABLE (well, actually, the VAX A.M. sets it in small-caps :-) ). >foo2(b) >char *b[]; >{ Here, b has the type `pointer to pointer to char'. Although b was declared as `array ?? of pointer to char' (?? denotes missing information), it is a declaration for a formal parameter, and the compiler `adjusts' it according to the rvalue-promotion rule for arrays. As far as the compiler is concerned, you typed char **b; ---it completely forgets the empty []s, because this is a formal parameter. > int i; > /* LINE 2 */ printf("Entries %d\n",sizeof(b)/sizeof(char *)); sizeof(b) is the size of `char **' (since b was declared that way); the result of this division is unpredictable, but chances are it will be either 0 (on word-oriented machines) or 1 (on others). > for ( i = 0; i < 4; ++i ) printf("%d: %s\n",i,b[i]); This will print the four strings in the original a[]. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris