Expert C Programming

(Jeff_L) #1

every array carries around with it a bunch of information about its element size, dimensions, and
indices.


Given these definitions:


func( int * turnip){...}


or


func( int turnip[]){...}


or


func( int turnip[200]){...}


int my_int; / data definitions /


int * my_int_ptr;


int my_int_array[10];


you can legally call any of the function prototypes above with any of the following arguments. They
are often used for very different purposes:


Table 9-1. Common Uses of Array/Pointer Actual Parameters
Actual Argument in Call Type Common Purpose

func(&my_int ); (^) Address of an integer "Call-by-reference" of an int
func( my_int_ptr ); (^) A pointer to an integer To pass a pointer
func( my_int_array ); (^) An array of integers To pass an array
func(&my_int_array[i] ); (^) Address of an element of int array To pass a slice of an array
Conversely, if you are inside func(), you don't have any easy way of telling which of these
alternative arguments, and hence with which purpose, the function was invoked. All arrays that are
function arguments are rewritten by the compiler at compiletime into pointers. Therefore, any
reference inside a function to an array parameter generates code for a pointer reference. Figure 9-3 on
page 247 shows what this means in practice.
Interestingly, therefore, there is no way to pass an array itself into a function, as it is always
automatically converted into a pointer to the array. Of course, using the pointer inside the function,
you can pretty much do most things you could have done with the original array. You won't get the
right answer if you take the size of it, though.
You thus have a choice when declaring such a function. You can define the parameter as either an
array or a pointer. Whichever you choose, the compiler notices the special case that this object is a
function argument, and it generates code to dereference the pointer.
Programming Challenge

Free download pdf