Path: utzoo!utgpu!utstat!jarvis.csri.toronto.edu!mailrus!purdue!haven!adm!cmcl2!acf3!sabbagh From: sabbagh@acf3.NYU.EDU (sabbagh) Newsgroups: comp.lang.c Subject: Re: Clarification needed on Pointers/Arrays Message-ID: <889@acf3.NYU.EDU> Date: 22 Feb 89 14:54:00 GMT References: <1436@etive.ed.ac.uk> Reply-To: sabbagh@acf3.UUCP () Organization: New York University Lines: 66 In article <1436@etive.ed.ac.uk> sam@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!