如何计算2个地址之间的差异? [英] how to calculate the difference between 2 addresses ?

查看:66
本文介绍了如何计算2个地址之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谢谢

thanks

推荐答案

地址1 - 地址2?


在一段时间内写道:
Address1 - Address2?

In a little while wrote:

谢谢
thanks


"在一段时间内 < cp **************** @ yahoo.com写了留言

新闻:11 ************** ********@h48g2000cwc.googlegr oups.com
"In a little while" <cp****************@yahoo.comwrote in message
news:11**********************@h48g2000cwc.googlegr oups.com

谢谢
thanks



每个它们是一个整数类型并执行减法。


要覆盖可能的地址值,你需要一个指针大小的整数

类型它将需要是未签名的。


由于它是无符号的,你只能从较大的减去较小的,所以

你需要做一个if()测试确定哪一个更小之前做

减法。


PS。如果您在

帖子的正文中重复提问,它有助于提高可读性。


-

John Carson




在一段时间内写道:

In a little while wrote:

thanks
thanks



这取决于所涉地址的类型。例如,如果你试图以
计算2个整数的偏移量,你需要将它们的相应地址减去

,然后通过sizeof(int)多次减去

获得一个字节大小的定量值(如果那就是你得到的
)。


一个对象的指针是绑定到它的类型。这就是指针如何找到下一个元素。

所以你需要解释两个地址之间的区别是什么意思,

因为在C ++中说话,这意味着就所涉及的对象而言。


你也可以忘记使用void *。


#include< iostream>


模板< typename T>

size_t差异(const T& r_lhs,const T& r_rhs)

{

return(& r_lhs - & r_rhs)* sizeof(T);

}


int main()

{

int m(0);

int * p_m =& m;

std :: cout<< p_m = << p_m<< std :: endl;

int o(0);

int * p_o =& o;

std :: cout<< ; p_o = << p_o<< std :: endl;


std :: cout<< 差异(p_m,p_o),以字节为单位:;;

std :: cout<<差异(p_m,p_o)<< std :: endl;

返回0;

}


/ *

p_m = 0x7fff628c8c54

p_o = 0x7fff628c8c44

差异(p_m,p_o)以字节为单位:16

* /


请不要被上述程序搞糊涂。这不是C ++程序员在典型的C ++代码中需要做的事情。此外,程序员

从不依赖于原语来获得一定的大小。

That depends of the types at the addresses involved. If you attempt to
calculate the offset of 2 integers, for example, you need to substract
their corresponding address and then mutiply by sizeof(int) in order to
obtain a byte-size quantitative value (if thats what you are getting
at).

An object''s pointer is bound to its type. Thats how a pointer does
++ptr to find the next element.
So you need to explain what you mean by difference between 2 addresses,
because in C++ speak, that means "in terms of the objects involved".

And you can forget using void* for that too.

#include <iostream>

template< typename T >
size_t difference(const T& r_lhs, const T& r_rhs)
{
return (&r_lhs - &r_rhs) * sizeof(T);
}

int main()
{
int m(0);
int* p_m = &m;
std::cout << "p_m = " << p_m << std::endl;
int o(0);
int* p_o = &o;
std::cout << "p_o = " << p_o << std::endl;

std::cout << "difference(p_m, p_o) in bytes: ";
std::cout << difference(p_m, p_o) << std::endl;
return 0;
}

/*
p_m = 0x7fff628c8c54
p_o = 0x7fff628c8c44
difference(p_m, p_o) in bytes: 16
*/

Please don''t be confused by the above program. This is not something a
C++ programmer needs to do in typical C++ code. Also, a programmer
never relies on a primitive to have some given size.


这篇关于如何计算2个地址之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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