Comp 210 Lab 10: Passing Vectors to Functions in C

We start with some code which adds up a particular, globally-defined vector vec, and from there we'll modify it.
// define some data:
int vec[] = { 8, 9, 10 };
int const size = 3;


int sum = 0;
for ( int i = 0;  i < size;  i = i + 1 ) {
  sum = sum + vec[i];
  }
To make this into a function, what are the two things we have to decide about the function? That's right -- what the function takes in, and what it returns. The return type for our vectorSum is clearly int. And the input type should ideally be "a vector of integers, of any length". This would be enough in Scheme, where you have vector-length to know how big any given vector is. However, C does not have such a function. So instead, when a function takes a vector as an argument, the function is passed not only the vector, but also the vector's length.

So we create a function whose arguments are "an array of of integers of unspecified size", and another integer (which does specify the size).

int vectorSum( int vec[], int size ) {
  int sum = 0;

  for ( int i = 0;  i < size;  i = i + 1 ) {
    sum = sum + vec[i];
    }

  return sum;
  }
This function could be called from somewhere else with just vectorSum( v, 3 ); (where of course v is a vector with three elements).
Back to Lab 10
Back to Comp 210 Home