Functional Arrays

The way we've been using strings with printf() suggests that we might be able to pass arrays as arguments to functions. And indeed we can. In particular if we want to pass an entire array as an argument, then we just put the array's name. For example, we might have an array like:
float samples[100];

and we could pass it to a function like this:
x = average(samples, num_samp);

We can also pass just a row of a two-dimensional array. The way to think about this is that a two-dimensional array is just an array of arrays. So we want to pass just one of those arrays.
for(i = 0; i < num_stud; ++i)
   process_student(names[i]);

where the names array is declared as:
char names[1400][30];

In other words, the name of a row of a two-dimensional array is the whole array name along with one index.

Being able to pass arrays as arguments is fine, but for it to be useful, we need to be able to declare functions that take arrays as arguments. We'll illustrate how by writing the averaging function we used above.


float average(float nums[], int n)
{
   float sum;
   int i;
   sum = 0.0;
   for(i = 0; i < n; ++i)
      sum += nums[i];
   return sum / n;
}

Here we see that to receive an argument that is an array, we need to give the type of elements the array contains, a formal name for the array and a set of square brackets. C will ignore any value we put there because it doesn't care. (Why it doesn't care is something that will have to be left for a later time.) Normally, then, we don't put anything there. (There is another equivalent syntax for this, but we don't need that until the next lesson .) As another example the prototype for the process student function might look like:
void process_student(char name[]);

Notice that in each case we give the single set of empty brackets for the declaration of the formal parameter even though in one case we're passing a whole one-dimensional array and in the other we're passing one row of a two-dimensional array. This again underscores the fact that a two-dimensional array is just an array of arrays and when we refer to one row of it, we are referring to a one-dimensional array.

It is possible to pass and receive two and greater dimensional arrays, but that involves one of the more subtle aspects of the C language so here we will simply say now that it can be done, but leave how to a later date.


Write a statement calling the function strcat() with the array buffer as the first argument and the name of student number i as the second where:
char buffer[80], names[1400][30];