i would like to find the size of integer array passed as an argument to a function. Here is my code
void getArraySize(int arr[]){ int len = (sizeof(arr)/sizeof(arr[0]) printf("Array Length:%d\n",len); } int main(){ int array[] = {1,2,3,4,5}; getArraySize(array); return 0; }
I am getting the following warning
sizeof on array function parameter will return size of 'int *' instead of 'int []' [-Wsizeof-array-argument]
Please help so that i can find the length of integer array inside the function
getArraySize
However am able to find the size of the array
inside the main
function.Since it is passed as a pointer
, am not able to find the length
from with in the function
.
i do have an idea though.I could put this with in a try/catch
block(C
does not have try catch,Only jumpers which is OS dependent) and loop until i get a segmentation fault
.
Is there any other way i could use to find the length of integer array
inside the function
The function clear() uses the idiom sizeof(array) / sizeof(array[0]) to determine the number of elements in the array. However, array has a pointer type because it is a parameter. As a result, sizeof(array) is equal to the sizeof(int *) .
Using sizeof() function to Find Array Length in C++ The sizeof() operator in C++ returns the size of the passed variable or data in bytes. Similarly, it returns the total number of bytes required to store an array too.
Inside the function ar is a pointer so the sizeof operator will return the length of a pointer. The only way to compute it is to make ar global and or change its name. The easiest way to determine the length is size(array_name)/(size_of(int). The other thing you can do is pass this computation into the function.
You cannot do it that way. When you pass an array to a function, it decays into a pointer to the first element, at which point knowledge of its size is lost.
If you want to know the size of an array passed to the function, you need to work it out before decay and pass that information with the array, something like:
void function (size_t sz, int *arr) { ... } : { int x[20]; function (sizeof(x)/sizeof(*x), x); }
The array decays to a pointer when passed.
So sizeof only works to find the length of the array if you apply it to the original array.
So you need to pass length of array as separate argument to function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With