C++: can't static_cast from double* to int*

前端 未结 5 2041
梦如初夏
梦如初夏 2020-12-17 10:01

When I try to use a static_cast to cast a double* to an int*, I get the following error:

invalid static_cast from type ‘double*’ to type ‘int*’
相关标签:
5条回答
  • 2020-12-17 10:20

    You should use reinterpret_cast for casting pointers, i.e.

    r = reinterpret_cast<int*>(p);
    

    Of course this makes no sense,

    unless you want take a int-level look at a double! You'll get some weird output and I don't think this is what you intended. If you want to cast the value pointed to by p to an int then,

    *r = static_cast<int>(*p);
    

    Also, r is not allocated so you can do one of the following:

    int *r = new int(0);
    *r = static_cast<int>(*p);
    std::cout << *r << std::endl;
    

    Or

    int r = 0;
    r = static_cast<int>(*p);
    std::cout << r << std::endl;
    
    0 讨论(0)
  • 2020-12-17 10:27

    Because you used double * instead of double

    The * after it means that you are declaring a pointer, which is vastly different from a regular double.

    C++ can not safely static_cast a pointer to a different type of pointer like that.

    If you are wanting to do this kinda thing, you must first dereference the variable.

    r=new int(static_cast<int>(*p));
    

    You must use new because a double and an integer can not reside in the same memory space(sanely)

    0 讨论(0)
  • 2020-12-17 10:30

    Floating point-to-integer conversion is supported, so int a = static_cast<int>(5.2) is fine. However, it's a conversion - the underlying data types are completely incompatible. What you're asking is for the runtime to convert a pointer to an 8-byte structure to a pointer to a 4-byte structure, which it can't do in any meaningful way.

    That having been said, if you really want to interpret your double as an integer, int* r = reinterpret_cast<int*>(p) will work fine.

    0 讨论(0)
  • 2020-12-17 10:30

    You can convert between a double and an int with static_cast<>, but not between pointers to different types. You can convert any pointer type to or from void * with static_cast<>.

    The rationale may be that int * and double * are often effectively arrays, and the implementation doesn't know how big the array is.

    0 讨论(0)
  • 2020-12-17 10:43

    Aside from being pointers, double* and int* have nothing in common. You could say the same thing for Foo* and Bar* pointer types to any dissimilar structures.

    static_cast means that a pointer of the source type can be used as a pointer of the destination type, which requires a subtype relationship.

    0 讨论(0)
提交回复
热议问题