#include<bits/stdc++.h>
using namespace std;
void foo(float a[]){
for(int i=0;i<5;i++){
cout<<a[i]<<endl;
}
}
int main()
{
int a[]={1,2,3,4,5};
foo((float*)a);
return 0;
}
I'm trying to pass an int array to a function accepting float array as typecast. But, the results are flabbergasted as I'm getting negative exponential floating number. Please help me with explaining what is happening to the function.
(float*)ayou should cast one by one and allocate another array with type float then convert(or cast) item by item(i mean you should write loop) from int to float. these link's may help you.stackoverflow.com/questions/15560790/… or this stackoverflow.com/questions/1908440/c-typecast-array.float". Unsurprisingly this does not yield the same result as casting the value via a type cast (static_cast<float>(*a)). Consider using a template to pass arrays of arbitrary type and cast them insidefoo:template <typename T> void foo(T[] a) { for(int i=0;i<5;i++){ cout<<static_cast<float>(a[i])<<endl; } }foo()assumes it is passed a pointer to the first element of an array of fivefloats, but it is actually passed the address of the first element of an array of fiveint. Without the "typecast", the compiler will issue a diagnostic at the call site. With the typecast, the compiler is effectively told not to issue a diagnostic. The typecast doesn't magically fix things to ensurefoo()is passed a valid array offloat.