Note that sizeof returns the total number of bytes. So for larger variable types such as ints, the for loop would look something like this.
for (i = 0; i < (sizeof(myInts)/sizeof(int)) - 1; i++) {
// do something with myInts[i]
}
sizeof(myInts)/sizeof(int))
return the number of elements, if use < not need remove 1 of return
if myInts is {1,2,3,4} the return is 4 not 5.
I know, you know, but example on http://arduino.cc/en/Reference/Sizeof are wrong,
I am create this post because I copy e use this example to explain sizeof() and long types to my friend and not work rigth.
I don´t know who I alert to change the page.
Note that sizeof returns the total number of bytes. So for larger variable types such as ints, the for loop would look something like this.
for (i = 0; i < (sizeof(myInts)/sizeof(int)) - 1; i++) {
// do something with myInts[i]
}
sizeof(myInts)/sizeof(int))
return the number of elements, if use < not need remove 1 of return
if myInts is {1,2,3,4} the return is 4 not 5.
You are completely correct and the Reference is definetely WRONG
Have look at file://arduino-1.0.1/reference/Sizeof.html
The examples given in the Reference are off by one
i < sizeof(myStr) - 1
i < (sizeof(myInts)/sizeof(int)) - 1
In the first example the iterator i will range from the first element of myStr to the element BEFORE the forelast element.
if myStr equals "Right" then the first referenced element would be 'R' and the last 'g' and not 't'. The last element of myStr is of course a null.
In the second example the last element is missed too, because of the same error. In C arrays normally index from element 0 to sizeof(array)-1. This is because counting starts at zero. If however the size is correctly calculated by sizeof(array)/sizeof(array_element) then the 'smaller then' operator '<' readily corrects for this and the '-1' makes this incorrect.
If think it is imperative that this textual error is corrected in the Reference manual, otherwise the manual is incorrectly named.