Search code examples
arraysmultidimensional-arrayarduinoarduino-idearduino-c++

Multi-dimensional Array Initialization in C


I'm piddling around with an Arduino and I have next to no programming in C. In looking through some example code I came across this array variable declaration:

byte myArray[][6] = {"0"};

I get that this is declaring an array with unspecified rows and 6 columns. What I don't understand is the {"0"}. Upon the execution of this like of code, what will this variable contain?

Thanks!


Solution

  • The expression will initialize an array that looks like this:

                   myArray[0][0]
                         ^
                         |   +----> myArray[0][1]
                         |   |
                       +---+----+---+---+---+---+
    myArray[0] ----->  |'0'|'\0'|   |   |   |   |
                       +---+----+---+---+---+---+
    

    As you don't specify the first dimension and you only initialze 1 line it defaults to byte myArray[1][6].

    If you were to initialize your array with, for instance:

    byte myArray[][6] = {"0", "1"};
    

    Then it would be:

                   myArray[0][0]
                         ^
                         |    +----> myArray[0][1]
                         |    |
                       +---+----+---+---+---+---+
    myArray[0] ----->  |'0'|'\0'|   |   |   |   |
                       +---+----+---+---+---+---+
    myArray[1] ----->  |'1'|'\0'|   |   |   |   |
                       +---+----+---+---+---+---+                    
                         ^    |
                         |    |
               myArray[1][0]  |
                              +--->myArray[1][1]
    

    In this case, because you initialize 2 lines, it defaults to byte myArray[2][6].