简体   繁体   English

int p = *(int *)i和int p = *(int *)&i之间的差异

[英]Difference between int p = *(int *)i and int p = *(int *)&i

The following question was asked in a recent microsoft interview. 在最近的一次Microsoft采访中,提出了以下问题。

What is the difference between the two declarations? 这两个声明有什么区别?

int p=*(int*)i; 
int p=*(int*)&i; 

I think in the first one i is a pointer and in the second one i is a variable. 我认为在第一个i是一个指针,并在第二个i是一个变量。
Is there anything else? 还有别的事吗?

The first is taking the value contained in i , treating it as a pointer, and retrieving whatever int value is at that address (if possible). 首先是获取i包含的值,将其视为指针,并检索该地址处的任何int值(如果可能)。

The second takes the address of i , casts it to pointer to int, and retrieves the value at that address. 第二个获取i的地址,将其转换为指向int的指针,并检索该地址处的值。 If i is an int , it's equivalent to p=i; 如果i是一个int ,则等效于p=i; . If it's not, it's going to take the first CHAR_BIT *sizeof(int) bits starting at the address of i , and (attempt to) treat them as an int , and assign whatever value that creates to p . 如果不是,它将从i的地址开始获取第一个CHAR_BIT *sizeof(int)位,并将其(尝试)视为int ,然后将创建的任何值赋给p

Edit: and yes, as @R. 编辑:是的,作为@R。 Martinho Fernandes pointed out, if i has an overloaded operator & , it may do something rather different from any of the above (ie, instead of the address of i it'll start with whatever its operator & returns). 马丁尼奥·费尔南德斯(Martinho Fernandes)指出,如果i有一个重载的operator & ,它可能会执行与上述任何operator &都完全不同的操作(即,代替i的地址,它将以其operator &返回的开头)。

If you know the language then this question boils down to what is the difference betweeen 如果您知道语言,那么这个问题可以归结为之间的区别是什么

i

and

&i

And the answer is that in the first case it's i and in the second case it's address of i , and then you have all those conversions to act on either of these two. 答案是,在第一种情况下,它是i ,在第二种情况下,它是i的地址,然后您需要所有这些转换来对这两个进行操作。

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

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