简体   繁体   English

如何将 integer 转换为常量 void 指针?

[英]How to cast an integer to a constant void pointer?

int getNumber(){
   int number;
   cin >> number;
   return number;
}
const void * getPointer(){
   const void *p = (const void *)getNumber();
   return p;
}

Gives me an error:给我一个错误:

warning: cast to pointer from integer of different size警告:从不同大小的 integer 转换为指针

and the console crashes控制台崩溃

How to cast an integer to a constant void pointer?如何将 integer 转换为常量 void 指针?

Start with an integer type that is wide enough to represent all pointer values.从足够宽以表示所有指针值的 integer 类型开始。 std::intptr_t is such type. std::intptr_t就是这种类型。 If you want to convert from a narrower type, then you can convert it to a wider type first.如果要从较窄的类型转换,则可以先将其转换为较宽的类型。 Then use reinterpret_cast.然后使用 reinterpret_cast。

and the console crashes控制台崩溃

The shown program is not the cause of that crash.显示的程序不是导致崩溃的原因。


Note that converting an integer to a pointer is an advanced technique that is rarely needed.请注意,将 integer 转换为指针是一种很少需要的高级技术。 If you are a beginner, then you likely are facing the XY-problem .如果您是初学者,那么您可能会面临XY 问题

getNumber() returns a copy. getNumber() 返回一个副本。 You cast the copy to a pointer.您将副本转换为指针。 (There is a difference between the copy and the address of the copy, which is what the pointer should be) (拷贝和拷贝的地址是有区别的,指针应该是这个)

int nb = getNumber();
const void *cp_void = (const void *)nb; // this will not yield the expected result.
int *p_nb = &nb; // memory adress to variable .. but variable will go out of scope

As the comments suggest just dynamically allocating the int is not the answer and there is a very likely a design flaw (in the code not shown).正如评论所暗示的那样,只是动态分配 int 并不是答案,而且很可能存在设计缺陷(在未显示的代码中)。

The two snippets shown getNumber() and getPointer() are not enough for us to comment or improve on the rest of the program.显示的 getNumber() 和 getPointer() 两个片段不足以让我们对程序的 rest 进行评论或改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM