I'm new to c programming. I want to create a function that takes an integer array as argument and returns length of the array. I know that the code below calculates the length correctly.
int arr[] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]);
But if I create a function like below and pass the array as an argument, it doesn't work.
int length_of(int* arr) {
return sizeof(arr) / sizeof(arr[0]);
}
My guess is that I'm not passing the array into the function correctly. What is the correct way of implementing this?
Well, there's no way of getting this done from a function. Any array, passed to a function as argument will decay to a pointer type (to the first element). So, inside the called function, all you will get is a size of a pointer.
An indirect way of achieving this would be to have something called a sentinel value in the array, and from the called function, iterate over the array elements to find the sentinel value while incrementing a counter, and once found, take the length of that counter.
Here's what the standard says (C99 6.3.2.1/3 - Other operands - Lvalues, arrays, and function designators):
Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.
This means that pretty much anytime the array name is used in an expression, it is automatically converted to a pointer to the 1st item in the array.
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