了解指针、取消引用等

Understanding pointers, dereference etc

本文关键字:引用 取消 指针 了解      更新时间:2023-10-16
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 的内存位置。'int' 表示指针指向一个整数,因此我们可以取消引用它。

为什么"int pointerToInt = &justInt;"无效?如果我想将 mem 位置存储在普通整数中怎么办。它是 4 位上的 32 字节,那么有什么问题?取消引用普通 int 也是如此。

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

pointerToPointer指向的东西有类型 int * 。 指向X的类型是X*,所以指向int *的类型是int **


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

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

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