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

懵懂的女人 提交于 2019-11-29 05:37:52

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.

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;

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.

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.

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!