• 关于数组两个元素地址相减的问题


    #include<stdio.h>  
    
    int a[5]={1,2,5,9,8};
    
    main(){  
    		int m,n,l,q;
    		m = a-&a[3];
    		n = (char*)a-(char*)&a[3];
    		l = (int)a - (int)&a[3];
    		q = (int*)a - (int*)&a[3];
    
    		//&a[3] = a + 3;
    
    		
    		printf("Test the value of a is %d
    ",a);
    		printf("Test the value of &a[0] is %d 
    ",&a[0]);
    		printf("Test the value of &a[1] is %d 
    ",&a[1]);
    		printf("Test the value of &a[2] is %d 
    ",&a[2]);
    		printf("Test the value of &a[3] is %d 
    ",&a[3]);
    
    
    		printf("Test the value of m is %d 
    ",m);
    		printf("Test the value of n is %d 
    ",n);
    		printf("Test the value of l is %d 
    ",l);
    		printf("Test the value of q is %d 
    ",q);
    }  
    

      

    运行结果:

    查看反汇编的代码,发现:
    int nTmp = &a[4] - &a[0];
    00416B87  lea         eax,[ebp-28h] 
    00416B8A  lea         ecx,[arrayTmp] 
    00416B8D  sub         eax,ecx 
    00416B8F  sar         eax,2 
    00416B92  mov         dword ptr [nTmp],eax 
    原来,执行完数组地址相减运算后,还会执行算数右移指令,右移位数视参数类型而定,如int型右移2位,short型右移1位。都知道右移1位相当于除以2操作,右移2位等同于除以4。

    由此可见,两个数组元素地址相减,实际是获取两个元素数组元素的距离,而不是地址的距离。如果要计算地址距离,就直接强制类型转换:int nTmp = (char*)&a[4] - (char*)&a[0];

  • 相关阅读:
    零知识证明入门
    Vue入门语法(二)表单,组件,路由和ajax
    Vue入门语法(一)
    okexchain整体架构分析
    写了个unsigned Tx生成二维码的web站点
    metamusk与web3相关资料
    QRCode.js:使用 JavaScript 生成二维码
    js工程安装,发布等命令
    C语言学习笔记-9.结构体
    C语言学习笔记-8.指针
  • 原文地址:https://www.cnblogs.com/secondtononewe/p/6221754.html
Copyright © 2020-2023  润新知