Size Of an Array

Lets say i want to write a function that returns me the size of an array. some thing like

“”"

int calcNumberOfElements (int arr[]) {

int numberOfElements = sizeof(arr)/sizeof(int);

return numberOfElements;

}

“”"

since arrays are passed as a refernece , sizeof(arr) returns the size of int * rather than the array. So how can i modify this function to return me the number of elements in an array ?

for character array
you can write like

while(arr[i]!=’\0’){
i++;
return i;

but for integer array there is no such method to find size of array inside function
that’s why every time we pass size of array along with array in functions

seems like defining a macro works
#define NUMBER_OF_ELEMENTS(arr) (sizeof(arr) / sizeof(arr[0]))
and it works just fine when called as
int numberOfElements = NUMBER_OF_ELEMENTS(arr);
Can u please let me know , how it exactly works and also if it is a good practice to use such implementation ?

this is not what you ask
you ask to find size of arr inside function which is not possible

#define NUMBER_OF_ELEMENTS(arr) (sizeof(arr) / sizeof(arr[0]))
this is macro
it will work simillar to function

you can right it in main also
int n=(sizeof(arr))/sizeof(arr[0]);

sorry if my previous question wasn’t clear but my goal with extracting it out was to reuse the code and not have duplication incase i need it for some other array.
so the doubt i had is if macro also works as a function then why is it that inside the macro we can get sizeof(arr) while inside a function i can’t ?

macro works like function but it is a not function\

it is defined globally so it access arr directly
function are removed form memory after completion of function but this is not for macros

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.