Using an array as a function parameter in C++

Passing an array as a parameter in C++ function (fn) will result the passed array to become a pointer to the index 0 element ( they call it ‘decay of array’). Therefore using the array as a argument to get the length of the array by using ‘sizeof ‘ function is not possible. It will return an integer smaller than the array length. The user also have to provide the array length (n) as an argument to the fn.

So to get the array length, you have to do it in the main fn. Below is the C++ code for finding the index of the smallest element in an array. This is a partial program for the Hackerrank ‘Minimum Swap 2 ‘ problem. I have previously solved it using Python, but being a coding and electronic geek, I also want to solve it using C++.

#include<iostream>

using namespace std; 

double minSwap2( int *arr , int n){
	
	//int arr_len = sizeof(arr) / sizeof(arr[0]) ; 
	int smallestIndex = 0;
	
	//Get smallest element index
	for ( int i =1 ; i < n ; i++){
		if (arr[i] < arr[smallestIndex] ){
			smallestIndex = i ; 
		}			
	}
	//put smallest in index 0
	if ( arr [0] != 1){
		int a = arr[0];
		int b = arr[smallestIndex];
		a = a + b ;
		b = a - b ;
		a = a - b ; 
		arr[0] = a;
		arr[smallestIndex] = b;
		}
		//iterate thru array
		for ( int j =1 ; j < n ; j++){
			if (arr[j] != arr[j-1] +1 ){
				
			}
		}
		
	return smallestIndex; 
}



int main( )
{
	int arr [ ] = {4, 3, 18, 5, 2, 9, 41, 1, 6};
	
	int arrlen = sizeof(arr) / sizeof(arr[0]);
	
	int e = minSwap2( arr , arrlen);
	cout <<  e << endl ;
	
	
	return 0; 
}