Skip to content
Glenn Salaman edited this page Sep 16, 2020 · 2 revisions

Array Basics

An array lets you use multiple variables with an easy reference. Here's an example:

int my_array[5];

The square brackets tell the compiler that we're making an array...in this case, we get 5 integers, because the number 5 is inside the square brackets.

To use this array, we also use the bracket notation. C starts it's array references at zero, so for our example, my_array[0] is the first element and my_array[4] is the last. We can then use each array element just like any other variable. Here are a couple examples:

my_array[0] = 10;
my_array[1] = 20;
my_array[2] = my_array[0]+my_array[1];

For loops are very useful for array manipulation. Check out this example, where we'll set each array element to 10 plus it's index:

int i;

for (i=0; i<5; i++)
{
  my_array[i] = 10 + i;
}

Using #defines is a good practice for array sizing...consider this snippet, which is similar to the above snippet:

#define MY_ARRAY_SIZE 5

int my_array[MY_ARRAY_SIZE];

void setup( )
{
  int i;
  
  for (i = 0; i < MY_ARRAY_SIZE; i++)
  {
    my_array[i] = 10 + i;
  }
}

Declaration

You can specify initial values for your array when you declare it...using the curly braces. Here's one example

int my_array[] = {10, 11, 12, 13, 14};

When doing the declaration this way, you don't have to specify how big the array is...but you can. Here's another example:

#define MY_ARRAY_SIZE 5

int my_array[MY_ARRAY_SIZE] = {10, 11, 12};

Note that I've only defined the first three elements...the compiler will by default set the rest to zero.

Arrays as function parameters

You can pass arrays to functions...there are two notation styles for this, but we'll focus on one to start with. Here's a useful example:

void print_array(int input_array[], int count)
{
  int i;
 
  Serial.print("Printing array of size");
  Serial.println(count);

  for (i = 0; i < count; i++)
  {
    Serial.println(input_array[i]);
  }
 
  Serial.println("====  DONE ====");
}

Notice that when passing an array, the compiler doesn't intrinsically know it's size...so we have to provide that as a parameter. (I'm not going to tell you why until we do pointers)