Physics and Astronomy
Home Our Teaching Resources C programming arrayfun-ex.html

# More example of passing functions to arrays

## Using functions to set up and print an array

Here we declare an array inside of main() and pass it to two functions one on which gives the array some values, the other prints it to the screen.

```  //
// Demonstrate passing an array to functions
//
#include <stdio.h>
#define VALUES 4
// Note: the two forms of the prototype: one with the
// dimension, which is ignore, and one without.
void setuparray(int input[VALUES]);
void printarray(int output[]);

int main() {
int num[VALUES];

setuparray(num);
printarray(num);

return 0;
}

void setuparray(int input[VALUES]) {
int i;
// Initialise to uninteresting values
for (i = 0; i < VALUES; ++i)
input[i] = i;
}

void printarray(int output[]) {
int i;

for (i = 0; i < VALUES; ++i ) {
printf("%d\n", output[i]);
}
}
```
```Step through this code

```

Realistically this gives us a slight problem: printarray() has a loop and we need to know when it finishes so in practice we are likely to write:

```void printarray(int output[], int n);
```

here n may be less than or equal to the true size of the array but should not be larger!

## Passing the wrong array size

We can illustrate what happens when we pass the wrong array size to a function: unsurprisingly it's much like the example in the main lectire, whatever follows it just gets trashed.

```  #include <stdio.h>
#include <math.h>

#define NA 2
#define NB 3
#define NC 4

void normalise(float p[], int n);

int main() {
float a[NA] = {2.7, 5.3};
float b[NB] = {5.8, 2.9, 3.0};
float c[NC] = {-9.6, 1.4, 13.9, 6.41};

normalise(a, NA);
normalise(b, NC); // Oops!
normalise(c, NC);

// More stuff here..

return 0;
}

// Normalise a vector (an array) of length n
void normalise(float p[], int n) {
float norm = 0;
int i;

for(i = 0; i < n; ++i)
norm += p[i]*p[i];
norm = sqrt(norm);

if ( norm > 0) {
for(i = 0; i < n; ++i)
p[i] /= norm;
}
}
```
```Step through this code

```

Here passing the wrong size of b trashes the first element of c.