I want to find the size of any array type. My code is:
#include <iostream>
using namespace std;
template <typename t>
int some_function(t arr []){
int s;
s = sizeof(arr)/sizeof(t);
return s;
}
int main(){
int arr1 [] = {0,1,2,3,4,5,6,7};
char arr2 [] = {'a','b','c','d','e'};
int size;
size = some_function(arr1);
cout << "Size of arr1 : "<<size<<endl;
size = some_function(arr2);
cout << "Size of arr2 : "<<size<<endl;
return 0;
}
When I run this code on cpp.sh output is:
Size of arr1 : 2
Size of arr2 : 8
and when I run it on CodeBlocks and Visual Studio output is:
Size of arr1 : 1
Size of arr2 : 4
I want it to print the exact size of an array which is:
Size of arr1 : 8
Size of arr2 : 5
SOLUTION
I found the solution with the help of rsp and Cheersandhth.-Alf. I was passing the array by value which is implicitly converted to pointer. After reading this article and answer provided by rsp I passed the array by reference. So final code is:
#include <iostream>
using namespace std;
template <typename t, int s>
int some_function(t (&arr)[s]){
return s;
}
int main(){
int arr1 [] = {0,1,2,3,4,5,6,7};
char arr2 [] = {'a','b','c','d','e'};
int size;
size = some_function(arr1);
cout << "Size of arr1 : "<<size<<endl;
size = some_function(arr2);
cout << "Size of arr2 : "<<size<<endl;
return 0;
}
Thank you everyone for help...