理解指针,解除引用等

时间:2015-03-15 21:07:55

标签: c++

int _tmain(int argc, _TCHAR* argv[]){

int justInt = 10;
int* pointerToInt = &justInt; 
int** pointerToPointer = &pointerToInt; //Why are 2 asteriks necessary? I thought at first that's because it would actually just point to 'justInt', but I checked and it points to 'pointerToInt' as expected.



void* voidPointerToInt = &justInt; //Can't be dereferenced unless we specify type because it's void.

cout << *pointerToInt << "\n";


cout << *(int*)voidPointerToInt;// How do you put into English "*(int*)"? Not sure what it effectively does step-by-step except that it takes 4 bytes from the start of address and puts them into an int, however that works.

/*          //I took a look into the disassembly, don't really know it very well though.

mov         eax,dword ptr [voidPointerToInt] ;Eax stores the memlocation of voidPointerToInt as I watched the registers change. But I thought that the [] would dereference it? EDIT: I forgot that all variables in masm are pointers until you dereference them. So, if the [] weren't there then we would move a pointer to 'voidPointerToInt' into eax instead of its value.
mov         ecx,dword ptr [eax]              ;Ecx becomes 10, as it dereferences the 4 bytes stored at the begining of memlocation that eax stores.

;Not sure what the rest is for.
push        ecx                              
mov         ecx,dword ptr ds:[0EF10A4h]      
call        dword ptr ds:[0EF1090h]  
cmp         esi,esp  
call        __RTC_CheckEsp (0EE1343h)  
*/

cin.ignore();

}

pointerToInt存储justInt的内存位置。 &#39; int&#39;表示指针指向一个整数,因此我们可以取消引用它。

为什么&#34; int pointerToInt =&amp; justInt;&#34;无效?如果我想将mem位置存储在普通int中,该怎么办?这是32位的4个字节,那么问题是什么?取消引用普通的int也是如此。

int *和存储内存地址的普通int之间会有区别吗?

1 个答案:

答案 0 :(得分:1)

pointerToPointer指向的内容具有int *类型。指向X的类型为X*,因此指向int *的类型为int **


cout << *(int*)voidPointerToInt;cout << *pointerToInt具有相同的效果。 void *是通用指针类型;你可以认为它有一个没有标记的变体,如果这会有所帮助。它可以用于通过公共接口传输不同类型的指针。

在您的代码中,您将pointerToInt转换为void *,然后返回其原始类型int *,恢复原始值。

使用代码:可以说如果X的类型为int *,那么(int *)((void *)X) == X