Next: Multi-dimensional arrays Up: Arrays and Pointers Previous: Character strings

Passing arrays as parameters

When we wish to pass an array as a parameter to a function, we do this by passing a single value, namely a pointer to the start of the array. We can do this by just using the array name.

Example

Here is our attempt at the system routine strlen:

int strlen(char *s)  /* return length of string s */
     /* or char s[]  */
{
int n;

for (n= 0; *s != '\0'; s= s + 1)
   n= n + 1;

return(n);
}

Notes

1. If you want to pass part of an array, then you can use a parameter such as &a[2] (or, the same thing, +).

2. The two formal parameters char *s and char s[] are exactly equivalent semantically. Which you use depends really on which way you are thinking, in terms of pointers or in terms of arrays.

3. Where a function always operates on an array of a particular size, this should be made clear with a formal parameter such as:

   double frequency[20];

Better still, #define the array size and use this name to limit loops etc using the array.

4. Once you have passed the array pointer into a function, it is held in a local variable. So you can change it there, unlike the (constant) actual arrray name, but only within the scope of the function of course.

5. You can have arrays of anything, including arrays of pointers. Hence it is a natural, common practice in C to implement multi-dimensional arrays that way.



Next: Multi-dimensional arrays Up: Arrays and Pointers Previous: Character strings


maspjw@
Tue Sep 27 15:29:34 BST 1994