Hi,
I am trying to program a function to calculate the next item in an array. For the last item the next one should be 0.
This should be simple, but I don't know how to check for the last item.
int nextItem(int item)
{
if (array[item + 1]) {
return item + 1;
} else {
return 0;
}
}
I have read some posts about calculating the length of the array by its memory consumption, but isn't there an easier way?
Is there a way to pass on the pointer to an array to merge this code into one function?
Is this correct?
int nItems (byte *pArray)
{
return sizeof(*pArray) / sizeof(*pArray[0]);
}
byte array[] = {1,2,3,4,5};
int number = nItems(array);
// number should be 5
No. Your example is taking the size of a pointer (2 bytes on an arduino). A pointer is nothing but an address of a memory location - there is no extra information carried about what it's pointing to, such as the size of an array. Rob's example works because he is taking the size of an array that is known at compile time. Once you pass a pointer to that array to a function though, the function has no idea how large the array is.
Could someone give me a little more explanation on this? I am posting what I understand but, some of this I do not understand. I need help with part with the question marks.
int array[6] = {2, 4, -8, 3, 2}; //array to be measured by sizeof
nItems = sizeof(array) / sizeof(array[0]);
//nltems = 6 divided by 2?????????
int nextItem(int item)
{
if (item == nItems -1)
//if the int item equals the result for nltems - 1 do action?????
// last item, do nothing
return 0;
....
}
sizeof returns size in bytes, so in your example, your array of 6 ints occupies 12 bytes. Hence, you have to divide it by the size of the first (or any other) element - two, to get the number of items it contains.