First, I read that:
array&array&array[0]
will all be the same as long as “array” is really an array.
So I tried:
int main(){
char ar[]={'a','b','c','\0'};
printf("argument: &ar %s\n",&ar);
printf("argument: &ar[1] %s\n",&ar[1]);
}
the output:
argument:&ar abc
argument:&ar[1] bc
It seems that &ar is taken as a pointer to the first element instead of a pointer to “ar”, which itself is a pointer to the first element if I am not mistaken.
’cause that shouldn’t be how &(pointer to a char) are treated, I tried:
char a='s';
char *pa=&a;
printf("argument: &pa %c\n",&pa);
The output for %c isn’t even a character.
Nor shouldn’t it be how a pointer to the first element of an array treated. I tried:
char *pa=&ar[0];
char **ppa= &pa;
printf("argument: &pa %s\n", ppa);
The output for %s is, not surprisingly, nonsense; but why hasn’t &ar been nonsense? For if ar were a pointer, shouldn’t &ar be as much a pointer to a pointer as is ppa?
My questions:
- Is simply “&” ignored when put before an array name?
Are array names simply special on this? - If so, how does the compiler verify that the identifier following “&” is a reference to an array? Does it actually search for it in a list of arrays so for declared?
You are mistaken.
&aris a pointer to the arrayar, but the arrayaris not a pointer of any sort (it’s an array), so&aris not a pointer to a pointer.An array is a contiguous sequence of objects – in the case of
ar, it’s a contiguous set of 4chars.&aris a pointer to this set of 4 chars, which necessarily means it points at the same place as&ar[0], a pointer to the firstcharin that set. It has a different type, though:&arhas typechar (*)[4]which means “pointer to array of 4 chars” and&ar[0]has typechar *, which means “pointer to char”.The confusion arises because in almost all expressions,
arevaluates to a pointer to the first element of the array (the exceptions to this are when it’s the operand of the unary&operator or thesizeofoperator). This doesn’t mean thataris a pointer though – it’s not – just that in most cases it evaluates to a pointer value.