Go Down

Topic: Error is sizeof code (Read 960 times) previous topic - next topic


Mar 03, 2012, 10:23 am Last Edit: Mar 03, 2012, 11:33 pm by AWOL Reason: 1

Code: [Select]
for (i = 0; i < (sizeof(myInts)/sizeof(int)) - 1; i++) {
  // do something with myInts[i]
The -1 is not needed for an int  array.


Mar 03, 2012, 09:08 pm Last Edit: Mar 03, 2012, 11:34 pm by AWOL Reason: 1
In that same example it should probably be made clear that "sizeof(myStr)" includes the null terminator which is why the -1 is appropriate there.

A slightly more robust way of determinig the number of elements in an arbitrary array:
Code: [Select]

sizeof myArray / sizeof myArray[0]

That way if the data type of the array is changed the code still works
Send Bitcoin tips to: 1G2qoGwMRXx8az71DVP1E81jShxtbSh5Hp


I usually put something like this

Code: [Select]
#define ARY_LEN(a) (sizeof(a)/sizeof(a[0]))

whenever my code has to work wiht arrays... i.e. very often. Would't it be nice to have a similar (better worded, perhaps) macro in Arduino.h and documented in Reference ?

Just my 2 cents, anyway...

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131