Expert C Programming

(Jeff_L) #1

when an array is a pointer...why the confusion?...an "array name in an expression" is a pointer...why C treats array subscripts as pointer offsets...an "array
name as a function parameter" is a pointer...why C treats array parameters as pointers...how an array parameter is referenced...indexing a slice...arrays and
pointers interchangeability summary...C has multi-dimensional arrays...but every other language calls them "arrays of arrays"...how arrays are laid out in
memory...how to initialize arrays...some light relief—hardware/software trade-offs


When an Array Is a Pointer


An earlier chapter emphasized the most common circumstance when an array may not be written as a
pointer. This chapter starts by describing when it can. There are many more occasions in practice
when arrays are interchangeable with pointers than when they aren't. Let us consider "declaration" and
"use" (with their conventional intuitive meanings) as individual cases.


Declarations themselves can be further split into three cases:



  • declaration of an external array

  • definition of an array (remember, a definition is just a special case of a declaration; it
    allocates space and may provide an initial value)

  • declaration of a function parameter


All array names that are function parameters are always converted to pointers by the compiler. In all
other cases (and the main interesting case is the "defined as an array in one file/declared as a pointer in
another" described in the previous chapter) the declaration of an array gives you an array, the
declaration of a pointer gives you a pointer, and never the twain shall meet. But the use (reference in a
statement or expression) of an array can always be rewritten to use a pointer. A diagram summary is
shown in Figure 9-1.


Figure 9-1. When Arrays are Pointers

However, arrays and pointers are processed differently by the compiler, represented differently at
runtime, and may generate different code. To a compiler, an array is an address, and a pointer is the
address of an address. Choose the right tool for the job.

Free download pdf