See the below explanation about Arrays from Arduino's official site:
Creating (Declaring) an Array
All of the methods below are valid ways to create (declare) an array.
int myInts[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 myInts.
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.
I have the following problems to understand:
Isn't
int mySensVals[6] = {2, 4, -8, 3, 2};
wrong? I count 5 elements.Isn't
char message[6] = "hello";
is wrong as well? I count 5 elements.
-
1The last sentence answers your second question.gre_gor– gre_gor2017年01月25日 14:36:10 +00:00Commented Jan 25, 2017 at 14:36
1 Answer 1
1-) Isn't int mySensVals[6] = {2, 4, -8, 3, 2}; wrong? I count 5 elements.
No, not wrong at all. There are 6 elements (as the definition says), and the first five are set to 2, 4, -8, 3 and 2. The sixth is undefined.
2-) Isn't char message[6] = "hello"; is wrong as well? I count 5 elements.
No. There are 6 there. To quote your quote:
Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character.
So "hello" is actually "hello0円".
-
You wrote "So "hello" is actually "hello0円". This 0円 also is required in C or only in Arduino?user1245– user12452017年01月25日 15:57:12 +00:00Commented Jan 25, 2017 at 15:57
-
It's standard C. The only thing that Arduino provides is advanced helper functions and macros such as
digitalWrite()
. EVERYTHING else is either C or C++. Arduino does not have its own language. It is merely a library.Majenko– Majenko2017年01月25日 15:58:17 +00:00Commented Jan 25, 2017 at 15:58 -
So you mean in plain C if I declare: char message[5] = "hello"; Is this wrong? since there is 0円 at the end? If so strange that I never noticed this before.user1245– user12452017年01月25日 16:00:03 +00:00Commented Jan 25, 2017 at 16:00
-
Yes, that is wrong. That would end up with functions like Serial.print() failing and printing lots of junk.Majenko– Majenko2017年01月25日 16:00:59 +00:00Commented Jan 25, 2017 at 16:00
-
By convention, in C, character strings (not "String" objects) are terminate with a 0円. 0円 is not otherwise a valid character, so it is used to mark the end of the text. The alternative is that you'd always have to pass not only the string, but it's length as well, which gets cumbersome and is an opportunity to make errors.JRobert– JRobert2017年01月25日 18:51:05 +00:00Commented Jan 25, 2017 at 18:51