其他分享
首页 > 其他分享> > 021 指针思考

021 指针思考

作者:互联网

 

/*
目录:
   一 C原理
   二 汇编原理
*/


一 C原理

void change(int** p2)
{
    printf("p2 = 0x%x, *p2 = 0x%x\n", p2, *p2);
    printf("*p2 = 0x%x, *8p2 = %d\n", *p2, **p2);
}

int main()
{
    int i = 3;
    printf("&i = 0x%x, i = %d\n", &i, i);


    int    *p = &i;
    printf("p = 0x%x, *p = %d, &p = 0x%x\n", p, *p, &p);
    change(&p);
    
    return 0;
}
/*
// result
    &i = 0x293cfba4, i = 3
    p = 0x293cfba4, *p = 3, &p = 0x293cfbc8
    p2 = 0x293cfbc8, *p2 = 0x293cfba4
    *p2 = 0x293cfba4, *8p2 = 3
*/

 

/*
内存: 数值; 地址(数值所在的内存单元编号)。
方法: 
    (1) &p: 取该p变量的地址。
    (2) *p: 把p当做某个地址看。
            取该p地址里面的值。
 
思考:
    1 *P: 得到数值可能是数值或指针。
    2 为什么可以跨函数修改数值内容,因为传递的是内存地址,不受函数作用域影响。
*/

 

二 汇编原理

; 汇编 
void change(int** p2)
{
    printf("p2 = 0x%x, *p2 = 0x%x\n", p2, *p2);
00007FF623E224FF  mov         rax,qword ptr [p2]  
00007FF623E22506  mov         r8,qword ptr [rax]  ; 数值: *p2
00007FF623E22509  mov         rdx,qword ptr [p2]  ; 数值: p2
00007FF623E22510  lea         rcx,[string "p2 = 0x%x, *p2 = 0x%x\n" (07FF623E2BC10h)]  
00007FF623E22517  call        printf (07FF623E2124Eh)  
    printf("*p2 = 0x%x, *8p2 = %d\n", *p2, **p2);
00007FF623E2251C  mov         rax,qword ptr [p2]  
00007FF623E22523  mov         rax,qword ptr [rax]  
00007FF623E22526  mov         r8d,dword ptr [rax]   ; 数值: **p2
00007FF623E22529  mov         rax,qword ptr [p2]  
00007FF623E22530  mov         rdx,qword ptr [rax]   ; 数值: *p2
00007FF623E22533  lea         rcx,[string "*p2 = 0x%x, *8p2 = %d\n" (07FF623E2BCE0h)]  
00007FF623E2253A  call        printf (07FF623E2124Eh)  
}


int main()
{
    int i = 3;
00007FF623E2211D  mov         dword ptr [i],3  
    printf("&i = 0x%x, i = %d\n", &i, i);
00007FF623E22124  mov         r8d,dword ptr [i]  ; 数值: i
00007FF623E22128  lea         rdx,[i]            ; 数值: &i
00007FF623E2212C  lea         rcx,[string "&i = 0x%x, i = %d\n" (07FF623E2BCF8h)]  
00007FF623E22133  call        printf (07FF623E2124Eh)  


    int    *p = &i;
00007FF623E22138  lea         rax,[i]               ; 数值: &i
00007FF623E2213C  mov         qword ptr [p],rax     ; 数值: p = &i
    printf("p = 0x%x, *p = %d, &p = 0x%x\n", p, *p, &p);
00007FF623E22140  lea         r9,[p]                ; 数值: &p
00007FF623E22144  mov         rax,qword ptr [p]     ; 
00007FF623E22148  mov         r8d,dword ptr [rax]   ; 数值: *p
00007FF623E2214B  mov         rdx,qword ptr [p]     ; 数值: p
00007FF623E2214F  lea         rcx,[string "p = 0x%x, *p = %d, &p = 0x%x\n" (07FF623E2BD10h)]  
00007FF623E22156  call        printf (07FF623E2124Eh)  
    change(&p);
00007FF623E2215B  lea         rcx,[p]               ; 数值: &p
00007FF623E2215F  call        change (07FF623E21532h)  
    
    return 0;
00007FF623E22164  xor         eax,eax  
}

 

/*
分析: 查看汇编指令和上面C原理一模一样。
*/

 

标签:p2,mov,021,rax,思考,printf,ptr,0x%,指针
来源: https://www.cnblogs.com/huafan/p/16421854.html