Page 65 - Programming the Photon Getting Started With the Internet of Things
P. 65

Arrays  are  a  way  of  containing  a  list  of  different  values.  This  is  unlike  what  we  have
        learned before, where variables contained only a single value, usually an int data type. In

        contrast to this, an array contains a list of values, and you can easily access any one of
        those values by its particular position in the array. In most programming languages, and in
        fact computer science in general, the first value is always represented as a 0 rather than a
        1; this means that the first variable is actually element zero. Here are some examples of
        how to declare an array in your code:


        int myValue[6];

                   int myPins[] = {2, 4, 8, 3, 6};
                   int mySensVals[6] = {2, 4, -8, 3, 2};
                   char message[6] = "hello";


        You can declare an array without initializing it, as in myValue. In myPins we declare an
        array without explicitly choosing a size. The compiler counts the elements and creates an
        array  of  the  appropriate  size.  Finally  you  can  both  initialize  and  size  your  array,  as  in

        mySensVals. Note that when declaring an array of type char, one more element than your
        initialization is required to hold the required null character.

             Arrays are zero indexed—that is, referring to the array initialization earlier, the first

        element of the array is at index 0, hence mySensVals[0] == 2, mySensVals[1] == 4, and
        so forth.

             It also means that in an array with 10 elements, index nine is the last element. Hence:


        int myArray[10]={9,3,2,4,3,2,7,8,9,11};
             // myArray[9]    contains 11
             // myArray[10]   is invalid and contains random information (other mem

        ory address)

        For this reason, you should be careful in accessing arrays. Accessing past the end of an
        array  (using  an  index  number  greater  than  your  declared  array  size)  is  reading  from

        memory that is in use for other purposes. Reading from these locations is probably not
        going  to  do  much  except  yield  invalid  data.  Writing  to  random  memory  locations  is
        definitely  a  bad  idea  and  can  often  lead  to  unhappy  results,  such  as  crashes  or  your
        program malfunctioning. This can also be a difficult bug to track down.




        Strings


        A string is a sequence of characters and a way for your Photon to deal with text. It is
        highly unlikely that we would use strings within our code—possibly if you are using a

        liquid crystal display (LCD) display, then a string might come into play.

             All of the following are valid declarations for strings:
   60   61   62   63   64   65   66   67   68   69   70