微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

这是一个将指针算术减成数组的问题

如何解决这是一个将指针算术减成数组的问题

printf("%d ",*(q-3));printf("%d ",q-p);输出应导致进入163,但编译器将打印74

您能向我解释一下计算如何进行吗?


#include<stdio.h>

int main(){
    int a[] = {5,16,7,89,45,32,23,10};
    int *p = &a[1];
    int *q = &a[5];
    printf("%d ",*(p+3));
    printf("%d ",*(q-3));
    printf("%d ",q-p);
    printf("%d ",p<q);
    printf("%d ",*p<*q);

    return 0;
}

解决方法

希望这会回答您的问题。查看输出并阅读代码中添加的注释以更好地理解。

#include <stdio.h>
#include <string.h>
#include<stdio.h>

int main(){
    int a[] = {5,16,7,89,45,32,23,10};
    int noe = sizeof(a) /sizeof(a[0]);
    int count = 0;
    
    int *p = &a[1]; 
    int *q = &a[5];
    
    while(count < noe)
    {
        printf("&a[%d] = %p and value there is %d\n",count,&a[count],a[count]);
        count++;
    }
    /* pointer arithmetic: when you subtract/add integers from pointers 
     resultant size = size of datatype * number of movements
     in this case,size of datatype(int) = 4,number of movements = 3 so i.e,12
     bytes will be moved backwards (since substraction) */

    printf("address  yeilding (q-3) =%p and value at *(q-3) = %d\n",(q-3),*(q-3)); 
    printf("address  of q = %p and address of p = %p and  q-p = %d\n",q,p,q-p); // 4
    return 0;
}

样品输出

&a[0] = 0x7fffeb35b600 and value there is 5
&a[1] = 0x7fffeb35b604 and value there is 16
&a[2] = 0x7fffeb35b608 and value there is 7
&a[3] = 0x7fffeb35b60c and value there is 89
&a[4] = 0x7fffeb35b610 and value there is 45
&a[5] = 0x7fffeb35b614 and value there is 32
&a[6] = 0x7fffeb35b618 and value there is 23
&a[7] = 0x7fffeb35b61c and value there is 10
address  yeilding (q-3) =0x7fffeb35b608 and value at *(q-3) = 7
address  of q = 0x7fffeb35b614 and address of p = 0x7fffeb35b604 and  q-p = 4

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。