Introduction to Computer Science - Fall 2004

Passing Arrays to Functions

Example 1

#include<stdio.h >
#define SIZE 5
void func(int n[], int size);

int main(){
    int num[SIZE] = {1, 2, 3, 4, 5};      /* num is an array of SIZE integers*/
    int i;

    /* before function call the elements of the array are: */
    for (i = 0; i < SIZE; i++){
      printf("%d ", num[i]);
    }
    printf("\n");

    /* function call */
    func(num, SIZE);

    /* after function call the elements of the array are: */

    for (i = 0; i < SIZE; i++){
      printf("%d ", num[i]);
    }
    printf("\n");

    return 0;
}

/* function definition */

void func(int n[], int size){
    for (i = 0; i < size; i++){
      n[i]++;
    }
}