Clarification needed on Pointers/Arrays

Chris Torek chris at mimsy.UUCP
Thu Feb 23 16:11:40 AEST 1989


In article <1436 at etive.ed.ac.uk> sam at 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 <type,value> pair% <array 4 of pointer to char,
[aggregate, not displayed]>.  In each call, this is converted to the
rvalue <pointer to pointer to char, &a[0]>.
-----
% 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 at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list