Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Mar 2005
    Location
    Indiana (USA)
    Posts
    50
    Thanks
    4
    Thanked 0 Times in 0 Posts

    C++ Type Casting

    I am having some trouble casting from float to float* in C++.

    Here is an example of what I have (and yes, I need to use float*):
    Code:
    float *MA[4];
    MA[0] = (float*)1.0F;

  • #2
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    You can't do that, the MA array is an array of pointers pointing to float variables. With that casting you are saying the address of the first variable that the pointer points to is 1.

    To use pointers like that you would have to do one of the following:
    Code:
    float first = 1.0F;
    float *MA[4];
    MA[0] = &first;
    Or

    Code:
    float *MA[4];
    MA[0] = new float;
    *(MA[0]) = 1.0F;
    With the last example of course you have to delete the pointer at some point before your program ends otherwise it will leak memory.
    OracleGuy

  • Users who have thanked oracleguy for this post:

    chiefbutz (11-25-2008)

  • #3
    New Coder
    Join Date
    Mar 2005
    Location
    Indiana (USA)
    Posts
    50
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Thanks, that fixed it. I have another question now. I am trying to multiply two float* types together, and I get the following compile error:

    error: invalid operands of types ‘float*’ and ‘float*’ to binary ‘operator*’
    any suggestions on that one?

  • #4
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    Yes, you need to de-reference the pointers before you multiply the numbers together. (You know with the *)
    OracleGuy


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •