Can somebody explain to me why I get 2 different values to ARRAY_SIZE before and after I pass the array to the function? How can I fix it?
What I would like to do is the calculate the size of the array I passed to the function not before
#define ARRAY_SIZE(array) ((sizeof(array))/(sizeof(array[0])))
int getSize(int arr[]) {
size_t i;
i = ARRAY_SIZE(arr);
return i;
}
setup() {
Serial.begin(9600);
int arr[] = {1, 2, 3, 4, 5};
Serial.println(getSize(arr),DEC); //return me a value of 2 WRONG
Serial.println(ARRAY_SIZE(arr),DEC); //return me a value of 5 CORRECT
}
1 Like
You get 2 different answers because you are asking 2 different questions. The function sizeof(arrray) returns the number of bytes in the array. When you use sizeof(array) / sizeof(array[0]) you will get the number of elements in the array.
int arr[] = {1, 2, 3, 4, 5};
Is an array of 5 elements, each element (int) takes 2 bytes so the array size is 10 bytes.
long arr[] = {1, 2, 3, 4, 5};
Is an array of 5 elements, each element (long) takes 4 bytes so the array size is 20 bytes.
1 Like
But even if you note that, you still have a problem. You can't really pass array's to functions! You just pass a reference to an array. And you simply can't determine the size from an array reference. Or to be precise, the only things that know the size of an array are you and the compiler, the Arduino knows nothing about the size. And the compiler can't determine the real size of an parameter array because it's not defined when you compile.
Google for "C++ array parameter" (or similar).
groundFungus:
You get 2 different answers because you are asking 2 different questions. The function sizeof(arrray) returns the number of bytes in the array. When you use sizeof(array) / sizeof(array[0] you will get the number of elements in the array.
Serial.println(getSize(arr),DEC); //return me a value of 2 WRONG // <<<<< WRONGER
Serial.println(ARRAY_SIZE(arr),DEC); //return me a value of 5 CORRECT
the function actually returns 1
the getSize() function is receiving a copy of a pointer to the array.
pointers are of size 2. the zeroeth element in the pointer (as an array) is 2bytes, arr[0] is an int, which are also two bytes, so function returns 2/2 = 1
try using an array of long int and see what happens...
Thank you all for your replies.
I did do check with DR. google find but could not understand where that issue lied.
At least I understand it better.
Summary: NOT POSSIBLE TO PASS ARRAY TO FUNCTION AND DETERMING ITS SIZE THERE because of how
it just too bad....
1 Like
sherzaad:
Summary: NOT POSSIBLE TO PASS ARRAY TO FUNCTION AND DETERMING ITS SIZE THERE because of how
it just too bad....
easily solved... just pass a pointer to the array and its size as two parameters.
1 Like