Array size

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

Does this mean if my array is an int, it doesn't have to be one bigger? So this would be fine:

buttonPin[7] = {13,12,11,10,5,9,6};

Thanks.

That's right. If you want 7 items you have an array of size 7.

You only need the extra one for "char" arrays which are intended to hold null-terminated strings.

Given the example who ever wrote that is mistaken.

buttonPin[7] = {13,12,11,10,5,9,6};

For all array of a single dimension the size is calculated as (sizeof(array)/sizeof(array[0]))

No trailing '\0' required.

lloyddean:
Given the example who ever wrote that is mistaken.

buttonPin[7] = {13,12,11,10,5,9,6};

For all array of a single dimension the size is calculated as (sizeof(array)/sizeof(array[0]))

No trailing ‘\0’ required.

Huh??? I’m lost. Are you speaking about my example? I thought it was ok, as nick mentioned.

SouthernAtHeart:

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

Does this mean if my array is an int, it doesn't have to be one bigger? So this would be fine:

buttonPin[7] = {13,12,11,10,5,9,6};

Thanks.

Or just skip the explicit size entirely. The compiler is pretty smart, eh.

const char mystring[] = "My string!";
const int buttonPin[] = { 13,12,11,10,5,9,6 };

SouthernAtHeart:

lloyddean: Given the example who ever wrote that is mistaken.

buttonPin[7] = {13,12,11,10,5,9,6};

For all array of a single dimension the size is calculated as (sizeof(array)/sizeof(array[0]))

No trailing '\0' required.

Huh??? I'm lost. Are you speaking about my example? I thought it was ok, as nick mentioned.

Yours is fine. You would need an additional slot if you were creating a string to be used in such functions like strcmp, strcpy, or other functions that accept a pointer to a character where null termination is expected.

SouthernAtHeart:
So this would be fine:

buttonPin[7] = {13,12,11,10,5,9,6};

Of course it should have a type, eg.

byte buttonPin[7] = {13,12,11,10,5,9,6};

And as maniacbug said, the compiler can figure out the size:

byte buttonPin[] = {13,12,11,10,5,9,6};

But if you need to know it, now you have to find it out, eg.

for (int i = 0; i < sizeof buttonPin; i++)
  pinMode (buttonPin [i], OUTPUT);

That only works if the array happens to be of “unit” sized things (like byte, char).

Otherwise as lloyddean said, you have to divide by the unit size:

for (int i = 0; i < (sizeof buttonPin) / (sizeof buttonPin [0]); i++)
  pinMode (buttonPin [i], OUTPUT);

I usually use a define to do that:

// number of items in an array
#define NUMITEMS(arg) ((unsigned int) (sizeof (arg) / sizeof (arg [0])))

So now you can do:

for (int i = 0; i < NUMITEMS (buttonPin); i++)
  pinMode (buttonPin [i], OUTPUT);

Thanks, that helps me understand it better, which is what I really needed.