问题描述
printf("%d ",*(q-3));
和printf("%d ",q-p);
的输出应导致进入16
和3
,但编译器将打印7
和4
。
您能向我解释一下计算如何进行吗?
#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