Arrays - C Interview Questions III

Q. Can you assign a different address to an array tag?
No, although in one common special case, it looks as if you can. An array tag is not something you can put on the left side of an assignment operator. (It's not an "lvalue," let alone a "modifiable lvalue.") An array is an object; the array tag is a pointer to the first element in that object.
For an external or static array, the array tag is a constant value known at link time. You can no more change the value of such an array tag than you can change the value of 7.
Assigning to an array tag would be missing the point. An array tag is not a pointer. A pointer says, "Here's one element; there might be others before or after it." An array tag says, "Here's the first element of an array; there's nothing before it, and you should use an index to find anything after it." If you want a pointer, use a pointer.
In one special case, it looks as if you can change an array tag:
void  f( char a[ 12 ] )
{
        ++a;    /* legal! */
}
The trick here is that array parameters aren't really arrays. They're really pointers. The preceding example is equivalent to this:
void  f( char *a )
{
        ++a;    /* certainly legal */
}
You can write this function so that the array tag can't be modified. Oddly enough, you need to use pointer syntax:
void  f( char * const a )
{
        ++a;    /* illegal */
}
Here, the parameter is an lvalue, but the const keyword means it's not modifiable.


Q. What is the difference between array_name and &array_name?
One is a pointer to the first element in the array; the other is a pointer to the array as a whole.
An array is a type. It has a base type (what it's an array of ), a size (unless it's an "incomplete" array), and a value (the value of the whole array). You can get a pointer to this value:
char a[ MAX ];      /* array of MAX characters */
char *p;            /* pointer to one character */
/* pa is declared below */
pa = & a;
p = a;  /* = & a[ 0 ] */
After running that code fragment, you might find that p and pa would be printed as the same value; they both point to the same address. They point to different types of MAX characters.
The wrong answer is
char *( ap[ MAX ] );
which is the same as this:
char *ap[ MAX ];
This code reads, "ap is an array of MAX pointers to characters."

Comments