C ++如何获取存储在void指针中的地址? [英] C++ how to get the address stored in a void pointer?

查看:467
本文介绍了C ++如何获取存储在void指针中的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取指针指向的值的内存地址?就我而言,这是一个空指针. 只是将其分配给一个uint会给我这个错误:

how can i get the memory address of the value a pointer points to? in my case it is a void pointer. just assigning it to an uint gives me this error:

Error   1   error C2440: 'return' : cannot convert from 'void *' to 'UInt32'

谢谢!

推荐答案

std::size_t address = reinterpret_cast<std::size_t>(voidptr);
// sizeof(size_t) must be greater or equal to sizeof(void*)
// for the above line to work correctly.


@Paul Hsieh
我认为在此特定问题中将void*转换为size_t就足够了,原因有以下三个:


@Paul Hsieh
I think it is sufficient to convert void* to size_t in this specific question for three reasons:

  • 发问者未指定他是否 是否需要便携式解决方案.他 说,这与他合作.我不知道到底是什么 那意味着 我很清楚他是 在Windows或其他平台上的IA-32上工作 系统处于保护模式.那 意味着将指针转换为 整数是对的定义操作 该系统,即使它不是由标准C ++定义的.

  • The questioner didn't specify if he wants a portable solution or not. He said, that it worked with him. I don't know exactly what that means but it is clear to me he is working on IA-32 on Windows or other system under protected mode. That means converting a pointer to an integer is a defined operation on that system even if it is not defined by standard C++.

第二,我建议先将指针转换为int,这显然毫无意义,因为 litb jalf 向我展示了.我更正了所犯的错误,并用size_t替换了int.

Second, I proposed first converting the pointer to int which is clearly meaningless as litb and jalf showed me. I corrected the mistake I've done, and replaced int with size_t.

最后,我努力寻找与您提议的标准解决方案相关的内容.不幸的是,我找不到任何相关的东西.我有以下参考资料: ANSI ISO IEC 14882 2003 .我认为Sellibitze指出,它将 作为即将到来的标准的一部分.我真的不了解C,显然C99引入了这种完美的解决方案.我希望有人向我展示一种使用C ++的可移植解决方案.

Finally, I tried my hard to find something relevant to what you proposed as a solution in the standards. Unfortunately, I couldn't find anything relevant. I have this reference: ANSI ISO IEC 14882 2003. I think sellibitze pointed out that it will be part of the coming standards. I really don't know about C, and obviously C99 introduced this perfect solution. I would like someone to show me a portable solution in C++.

请不要犹豫纠正我的错误,我仍然是uni的学生:)

Please, don't hesitate to correct my mistakes, I am still a student at uni :)

谢谢

这篇关于C ++如何获取存储在void指针中的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆