Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the size of int [] array

Tags:

c++

In the following function, how can we find the length of the array

int fnLenghthOfArray(int arry[]){
    return sizeof(arry)/sizeof(int); // This always returns 1
}

Here this function always returns 1. Where as, sizeof(arry)/sizeof(int) gives the actual length of the array, in the function where it is declared.

If we use vector or template like

template<typename T,int N> 

int fnLenghthOfArray(T (&arry)[N]){

}

we can get the size. But here I am not allowed to change the function prototype.

Please help me to find this.

like image 741
Sabeer Ebrahim Avatar asked Dec 01 '22 20:12

Sabeer Ebrahim


1 Answers

Remember, in C when you pass an array as an argument to a function, you're passing a pointer to the array. If you want to pass the size of the array, you should pass it as a separated argument.

The size of a pointer and an int is 4 or 8 or something else - depending on ABI.
In your case, it's 4, so you're getting sizeof(int *)/sizeof int which is 1.


Here is a useful trick

You can store the length of the array in the first element of it:

int myArray[]= {-1, 1, 2, 3, 4, 5};
myArray[0] = sizeof(myArray) / sizeof(myArray[0]) - 1;
//The -1 because.. the first element is only to indicate the size

Now, myArray[0] will contain the size of the array.

like image 132
Maroun Avatar answered Dec 03 '22 10:12

Maroun