Pages: [1]   Go Down
Author Topic: Error is sizeof code  (Read 769 times)
0 Members and 1 Guest are viewing this topic.
Niagara, Ontario, Canada
Offline Offline
Newbie
*
Karma: 0
Posts: 1
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

http://arduino.cc/en/Reference/Sizeof

Code:
for (i = 0; i < (sizeof(myInts)/sizeof(int)) - 1; i++) {
  // do something with myInts[i]
}
The -1 is not needed for an int  array.
« Last Edit: March 03, 2012, 05:33:33 pm by AWOL » Logged

Massachusetts, USA
Offline Offline
Tesla Member
***
Karma: 208
Posts: 8860
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
sizeof myArray / sizeof myArray[0]
That way if the data type of the array is changed the code still works
« Last Edit: March 03, 2012, 05:34:38 pm by AWOL » Logged

Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

0
Offline Offline
God Member
*****
Karma: 2
Posts: 596
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I usually put something like this

Code:
#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...
Logged

Pages: [1]   Go Up
Jump to: