如何根据大小取消引用?
我正在尝试打印地址指向的值,但问题是我需要根据传递给我的大小取消引用该指针。所以这样的事情:
void print(Address addr, Int size) {
...
}
我对如何实现这一目标有点困惑。有人能指出我正确的方向吗?
编辑: 好吧,我在想:
char p[80];
memset(p, '\0', 80);
memcpy(p, addr, size);
然后取消引用为 *p。如果有更好的方法或者正确的方法请告诉我
I am trying to print the value pointed to by an address but the problem is I need to dereference this pointer based on the size that is passed to me. So something of this sort:
void print(Address addr, Int size) {
...
}
I am a little confused on how to achieve this. Can someone point me in the right direction?
EDIT:
Ok so I'm thinking:
char p[80];
memset(p, '\0', 80);
memcpy(p, addr, size);
And then dereference as *p. If there is a better way or a correct way, please let me know
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的问题很不清楚。如果您的意思是要从传递的地址转储任意二进制数据,则需要类似以下内容:
或者如果您的意思是要打印非空终止的字符数据,请尝试:
Your question is very unclear. If you mean you want to dump arbitrary binary data from the address passed, you want something like:
Or if you mean you want to print character data that's not null-terminated, try:
如果它是一个数字(我认为是一个数字),那么您将需要这样的东西:
If it is a number, which I assume it is, you will need something like this:
您可以在例程中使用 switch 语句:(
“print”是打印各种大小的整数的例程,可能使用 C++ 多态性)
复杂的解决方案是使用 C++ 模板,例如使用参数类型
Integer
在调用时被实际变量类型替换。然后,此例程可能会作用于此 Integer 变量的大小(可能会在 1 到 8 之间变化,如果您自己实现更长的整数,则可能会更大)。这种方法的缺点是编译器为每种类型的参数生成一个例程实例,并且依赖于大小的逻辑将导致某些测试的“始终为真”条件。一个简单的方法是始终使用您期望的最长整数类型。You may use a switch statement in the routine:
("print" is a routine to print integers of various sizes, perhaps using C++ polymorphism)
A sophisticated solution is to use a C++ template e.g. using a parameter type
Integer
which is subsituted by the actual variable type upon invocation. This routine may then act on the size of thisInteger
variable (which may vary from 1 to 8, or more if you implement longer integers yourself). This disadvantage of this approach is that the compiler generates a routine instance for every type of argument, and logic dependent on the size will lead to "always true" conditions for some tests. An easy way out is to use always the longest type of integer you'd expect.