Multi-dimensional Array Initialization in C

249 views Asked by At

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!

2

There are 2 answers

0
anastaciu On BEST ANSWER

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].

0
luser droog On

The string literal "0" is equivalent to the compound literal (char[]){ '0', '\0' }. So the declaration is equivalent to:

byte myArray[][6] = { { '0', '\0' } };

So the resulting array will be one row that contains an ASCII 0 (or a 0 appropriate to whatever the target character set is) followed by 5 \0 or NUL bytes.