I recently embarrassed myself while explaining to a colleague why
char a[100];
scanf(\"%s\", &a); // notice a & in front of \'a\'
is ve
It's been a while since I programmed in C but here's my 2c:
char a[100]
doesn't allocate a separate variable for the address of the array, so the memory allocation looks like this:
---+-----+---
...|0..99|...
---+-----+---
^
a == &a
For comparison, if the array was malloc'd then there is a separate variable for the pointer, and a != &a
.
char *a;
a = malloc(100);
In this case the memory looks like this:
---+---+---+-----+---
...| a |...|0..99|...
---+---+---+-----+---
^ ^
&a != a
K&R 2nd Ed. p.99 describes it fairly well:
The correspondence between indexing and pointer arithmetic is very close. By definition, the value of a variable or expression of type array is the address of element zero of the array. Thus after the assignment
pa=&a[0];
pa
anda
have identical values. Since the name of the array is a synonym for the location of the initial element, the assignmentpa=&a[0]
can also be written aspa=a;