There is no way to determine the length inside the function. However you pass arr
, sizeof(arr)
will always return the pointer size. So the best way is to pass the number of elements as a separate argument.
sizeof
only works to find the length of the array if you apply it to the original array.
int arr[5]; //real array. NOT a pointer
sizeof(arr); // :)
However, by the time the array decays into a pointer, sizeof will give the size of the pointer and not of the array.
void getArraySize(int arr[]){
sizeof(arr); // will give the pointer size
}
There is some reasoning as to why this would take place. How could we make things so that a C array also knows its length?
A first idea would be not having arrays decaying into pointers when they are passed to a function and continuing to keep the array length in the type system.
When you pass an array to a function it decays to pointer. So the sizeof
function will return the size of int *
. This is the warning that your compiler complining about-
sizeof on array function parameter will return size of 'int *' instead of 'int []'
As i suggested when you pass the array to the function you need to pass the Number of elements also-
getArraySize(array, 5); // 5 is the number of elements in array
Catch it by-
void getArraySize(int arr[], int element){
// your stuff
}
Else general way to calculate array size-
void getArraySize(int arr[], int len){
// your stuff
printf("Array Length:%d\n",len);
}
int main(){
int array[] = {1,2,3,4,5};
int len = (sizeof(arr)/sizeof(arr[0]); // will return the size of array
getArraySize(array, len);
return 0;
}