Clarification needed on Pointers/Arrays
sabbagh
sabbagh at acf3.NYU.EDU
Thu Feb 23 00:54:00 AEST 1989
In article <1436 at etive.ed.ac.uk> sam at lfcs.ed.ac.uk (S. Manoharan) writes:
>
>main()
>{
> static char *a[] = { "123456789", "bull", "fred", "foo" };
> /* array of char-pointers */
>
> printf("Entries %d\n",sizeof(a)/sizeof(char *));
> foo1(a);
> foo2(a);
>}
>
>foo1(b)
>char *b;
>{
> int i;
>
> printf("Entries %d\n",sizeof(b)/sizeof(char *));
> /* LINE 1 */ for ( i = 0; i < 10; ++i ) printf("%d: %c\n",i,b+i);
>}
Since b is a pointer to char, b+i is a pointer to char also. Maybe you
want b[i]?
>
>foo2(b)
>char *b[];
>{
> int i;
> /* LINE 2 */ printf("Entries %d\n",sizeof(b)/sizeof(char *));
> for ( i = 0; i < 4; ++i ) printf("%d: %s\n",i,b[i]);
>}
>
In this case, sizeof(b) == sizeof(char **) (i.e. a pointer to a pointer to
char). Clearly, sizeof(char **) == sizeof(char *) is not unexpected (although, not required by the standard).
Now for my $0.02 on pointers vs. arrays:
Simply put, a pointer to blah should be considered a different type than blah.
Consider the following declarations:
char fred, *p1, **p2;
Then &fred returns char *; *p1 returns char; *p2 returns char *, etc.
Now, according to K & R, the notation
p1[j]
is in ALL WAYS equivalent to
*(p1 + j)
In fact, the compiler makes this transformation during parsing! (Incidentally,
this implies that p1[j] == j[p1]) !!
So what are arrays? They are POINTER CONSTANTS. That is, if you declare
char a[10]
then a == &a[0] is a constant; it is the address of the first element of the
array.
Moral of the story: you can treat pointers like arrays, but you can't treat
arrays like pointers!
More information about the Comp.lang.c
mailing list