Passing Arrays to Functions

Recall that when we pass (scalar) arguments to functions, we actually passed a copy of the value of the argument expression into a new cell allocated by the declaration in the header of the function. For example:
       int square(float x)
       {   return x * x;   }

called as
       area = PI * square(radius);

passes a copy of the value of the local variable, radius, to to cell called x, local to square().

But doing the same thing for arrays would be very inefficien, as well as inconsistent -

       display(data);
here, the variable, data, really refers to a pointer. In fact, that is exactly what is passed to the function - the pointer.

How do we declare the pointer in the header of display()?

We could declare it as a pointer:
       void display(int * d);
We can also use different syntax to make it clearer that we are passing an array:
       void display(int  d[]);
Notice the empty brackets. They indicate we are passing an array. The number of elements is not required, since we are NOT allocating memory for the array here; we are simply receiving a pointer to the block of storage allocated elsewhere.

The above two prototypes are exactly equivalent.

We can see this in the following simple example.


[up] to Overview.