Expert C Programming

(Jeff_L) #1

which clearly demonstrate the interchangeability of pointers and arrays.


It's too easy to overlook that this only happens in the specific context


of actual parameters in a function call. Worse, you can write


printf("array at location %x holds string %s",a ,a);


in which the same statement uses an array name as an address


(pointer) and as an array of characters. This only works because


printf is a function, so the array is passed as a pointer. We are also


accustomed to seeing the parameter of main declared as char **argv


or char *argv[] quite interchangeably. Again, this is only permitted


because argv is a function parameter, but it does lull the programmer


into wrongly concluding that "C is consistent and regular in its


approach to address arithmetic." When you add to this the detailed


and lengthy treatment of how subscripted array expressions can


always be written in terms of pointers, it is easy to see how the


confusion has arisen.


The box below is really important, and will be explained then referred to many times in this chapter
and the next one. Pay attention, mark the page, and be prepared to refer to it again several times!


Software Dogma


When Arrays Are Pointers


The C standard has the following to say about the matter.


Rule
1.

An array name in an expression (in contrast with a declaration) is treated
by the compiler as a pointer to the first element of the array [1] (paraphrase,
ANSI C Standard, paragraph 6.2.2.1).
Rule
2.

A subscript is always equivalent to an offset from a pointer (paraphrase,
ANSI C Standard, paragraph 6.3.2.1).
Rule
3.

An array name in the declaration of a function parameter is treated by
the compiler as a pointer to the first element of the array (paraphrase, ANSI

C Standard, paragraph 6.7.1).


[1] OK nitpickers, there are a few minuscule exceptions that concern arrays treated as a whole.


A reference to an array is not replaced by a pointer to the first element when:



  • sizeof()

  • &


Free download pdf