Hello dear Community,
I'm declaring an Array of ints like so:
int myInts[] = { 0,1,0,1,0,1,0,1 };
those are 8 values. Simple. But now when I ask for the size of the array with sizeof(myInts) I then get "16" printed out.
In setup I also tried to delete all previous values by using:
memset(myInts,0,sizeof(myInts));
but it still prints 16. Its not that big deal in this case, I'm just wondering how to get rid of some possible older values like previously declarated arrays with custom objects or something.
I also have been googling around before but couldn't find an answer.
Thanks for the advice!
Best
Marcel
sizeof tells you the size of the object you're measuring in bytes. Ints take up two bytes on your arduino, so your array is 16 bytes long.
But now when I ask for the size of the array with sizeof(myInts) I then get "16" printed out.
What did you expect? Why?
The function tells you how big the array is, not the number of elements in the array. The array is 8 * 2 bytes long, or 16.
If you want the number of elements in the array use sizeof(myInts) / sizeof(myInts[0]).
Ah ok! didn't even think about that. Thank you!
Along with what you learned here from wildbill and PaulS, you will sometimes see this macro:
#define ELEMENTCOUNT(x) (sizeof(x)/sizeof(x[0]))
which you can then use in code like:
for (i - 0; i < ELEMENTCOUNT(myArray); i++) {
// for loop statement body
}
If you have defined (NOT declared) a 10 element int array named myArray[], the first sizeof() operator returns the number of bytes allocated to the array (i.e., 20) while the second sizeof() returns the number of bytes for one element of the array (i.e., 2). As a result, the macro expansion returns the number of elements in the array (10 = 20 / 2). Using this allows you to change the array size in one place and not having to do a global search for its usage throughout the code.