为什么会这样? [英] Why is this happening?

查看:68
本文介绍了为什么会这样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  char  * Data =   0123456789; 
< pre> int i = 0 ;
std :: cout<< 当前地址:<<数据+ i<< \ n;





当我运行上面的代码时,显示的值是:

>当前地址:0123456789(这是'数据'的值)

它应该是数据指向的地址(即值'0'的地址)。

为什么会发生这种情况?我使用MSVC作为我的编译器。



谢谢。



编辑:我被建议使用'&',但'& Data'将返回变量的'Data'地址,而不是它指向的变量。



再次感谢。

解决方案

数据是一个指向char的指针 - 这意味着它包含一个内存地址,它是固定字符串中第一个字符的地址。这只是现实中的一个数字,但无论何时向任何指针添加值,系统都会查看指针的类型(在这种情况下为char *),计算出它指向的类型的大小(char,所以这是一个每个元素的字节数),将您添加的数字乘以元素大小(以字节为单位)(零,一次仍为零),并将该值添加到指针。



然后你将它传递给 cout - 它知道它是一个指向char的指针,因此显示字符串指向而不是地址本身。

为了证明这一点,更改

  int  i =  0 ; 

To

  int  i =  2 ; 

,输出将更改为:

当前地址:23456789 



如果你想要地址的价值(实际上毫无意义)首先将其转换为数值:

 std :: cout<<  当前地址:<< ( int )(Data + i)<<   \ n; 

你应该得到你想要的东西。


char* Data = "0123456789";
<pre>int i = 0;
std::cout << "Current Address: " << Data+i << "\n";



When i run the code above, the value displayed is:
>Current Address: 0123456789 (this is the value of 'Data')
Whereas it should be the address pointed to by data (ie address of the value '0').
Why is this happening? I use MSVC as my compiler.

Thanks.

Edit: I was suggested to use '&', but '&Data' will return the address of 'Data' the variable, not the of variable pointed by it.

Thanks again.

解决方案

Data is a pointer-to-char - which means it contains a memory address which is the address of the first character in your fixed string. That's just a number in reality, but whenever you add a value to any pointer, the system looks at the type of the pointer (char* in this case), works out the size of the type it points at (char, so that's one byte per element), multiplies the number you are adding by the size of an element in bytes (zero, times one is still zero), and adds that value to your pointer.

You then pass that to cout - which knows it is a pointer-to-char and so displays the string it points at instead of the address itself.
To prove this, change

int i = 0;

To

int i = 2;

and the output will change to:

Current Address: 23456789


If you want the value of the address (which is meaningless in reality) cast it to a numeric value first:

std::cout << "Current Address: " << (int) (Data+i) << "\n";

And you should get what you want.


这篇关于为什么会这样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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