How to Pass an Array as Parameter in C

Arrays as parameter

If you try to pass an array as a parameter to a function in C, you might find it difficult to iterate over that array. You might try sizeof and find that it isn't really giving you the size of your array. That is because arrays decay to pointers in function calls. Therefore, you must also pass the size of the array to your function. There are a few options for passing arrays to your function:

Method 1 - Pointer

int arrayFunction(int *arrayOfInts, int size) 
{
  printf("size: %d\n", size);
  for(int i = 0; i < size; i++) {
        printf("%d ", arrayOfInts[i]);
    }
}

Method 2 - Sized Array

int arrayFunction(int arrayOfInts[3], int size) 
{
  printf("size: %d\n", size);
  for(int i = 0; i < size; i++) {
        printf("%d ", arrayOfInts[i]);
    }
}

Method 3 - Unsized Array

int arrayFunction(int arrayOfInts[], int size) 
{
  printf("size: %d\n", size);
  for(int i = 0; i < size; i++) {
        printf("%d ", arrayOfInts[i]);
    }
}

Calling the function in any of these examples using this code:

#include <stdio.h>

int main()
{
  int arrayOfInts[] = {1,2,3};
  arrayFunction(arrayOfInts, sizeof(arrayOfInts)/sizeof(int));
}

results in:

size: 3
1 2 3