0

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:

  1. Isn't int mySensVals[6] = {2, 4, -8, 3, 2}; wrong? I count 5 elements.

  2. Isn't char message[6] = "hello"; is wrong as well? I count 5 elements.

  • 1
    The last sentence answers your second question. – gre_gor Jan 25 '17 at 14:36
3

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 "hello\0".

| improve this answer | |
  • You wrote "So "hello" is actually "hello\0". This \0 also is required in C or only in Arduino? – user1245 Jan 25 '17 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 Jan 25 '17 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 Jan 25 '17 at 16:00
  • Yes, that is wrong. That would end up with functions like Serial.print() failing and printing lots of junk. – Majenko Jan 25 '17 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 Jan 25 '17 at 18:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.