Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a function to return the length of an int array in C [duplicate]

Tags:

arrays

c

function

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?

like image 202
Atick Faisal Avatar asked Dec 23 '22 16:12

Atick Faisal


2 Answers

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.

like image 165
Sourav Ghosh Avatar answered Feb 24 '23 23:02

Sourav Ghosh


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.

like image 26
snr Avatar answered Feb 24 '23 22:02

snr