0
#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.

4
  • since float and int has diffrent size and array is sequence order of memory you cant cast like (float*)a you 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. Commented May 29, 2021 at 7:19
  • 1
    You're effectively telling the compiler: "I don't care what kind of data is actually stored at this memory location; just assume it was a 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 inside foo: template <typename T> void foo(T[] a) { for(int i=0;i<5;i++){ cout<<static_cast<float>(a[i])<<endl; } } Commented May 29, 2021 at 7:21
  • The behaviour is undefined, since foo() assumes it is passed a pointer to the first element of an array of five floats, but it is actually passed the address of the first element of an array of five int. 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 ensure foo() is passed a valid array of float. Commented May 29, 2021 at 7:24
  • BTW, all the array stuff is just a red herring. In particular the "function accepting float array" doesn't really take an array as parameter, you're just using an (IMHO) confusing syntax for something that is just a pointer. Commented May 29, 2021 at 7:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.