Go Down

Topic: sizeof() problem (Read 690 times) previous topic - next topic

Tim Stamp

Hi folks,

Code: [Select]
int variables[5] = {a,b,c,d,e};
Serial.println( sizeof(variables) );


Why does this block of code return 10?

Thanks in advance for your help.

kg4wsv

Because you have an array of 5 ints which are two bytes each.  5*2 = 10.

-j


Tim Stamp

Ahhhh that explains it... so is there a function to return how long an array is?

.. I think I'll start using char[] arrays seeing as the PWM pins only have 256-bit resolution. integers just seem too wasteful now.

Cheers!

kg4wsv

I think there was a discussion on that not too long ago, but I think sizeof(a)/sizeof(a[0]) will do it.

-j


halley

Code: [Select]

#define countof(a)   ( (sizeof(a) / sizeof(*(a)) )


I usually define this early on.  Then you can use countof(myarrayname) and get the number of elements in the array.  Note that you cannot tell how big an array is if you use a pointer instead.

Tim Stamp

ok, thanks for the ideas folks

Go Up