Go Down

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

quickwhitefox

Mar 03, 2012, 10:23 am Last Edit: Mar 03, 2012, 11:33 pm by AWOL Reason: 1
http://arduino.cc/en/Reference/Sizeof

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.

johnwasser

#1
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: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

mromani

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