C中的数组地址减法 [英] Array address subtraction in C
问题描述
可能重复:
C语言中的指针算术
代码:
int main()
{
int a[ ] ={0,1,2,3,4};
char c[ ] = {'s','a','n','j','u'};
printf("%d\n",&a[3]-&a[0]);
printf("%d\n",&c[3]-&c[0]);
return 0;
}
为什么两者的输出都为3 3,如果我们考虑地址的不同,两者的输出都将不同?
在指针算术中,减法返回的差值不是字节数,而是两个指针之间的指针类型.
因此,由于a[3]
和a[0]
之间的int
s差异与c[3]
和c[0]
之间的char
s差异相同-您对两者获得相同的结果.>
指针减法运算的算法类似于:
type* p1 = ...
type* p2 = ...
p1 - p2 == (((int)p1) - (int(p2))) / sizeof(type)
Possible Duplicate:
Pointer Arithmetic In C
Code:
int main()
{
int a[ ] ={0,1,2,3,4};
char c[ ] = {'s','a','n','j','u'};
printf("%d\n",&a[3]-&a[0]);
printf("%d\n",&c[3]-&c[0]);
return 0;
}
Why the output comes 3 3 for both, if we consider the difference in addresses they will be different for both??
In pointer arithmetics, subtraction return the difference not in bytes, but in the pointer's type between two pointers.
So, since the difference in int
s between a[3]
and a[0]
is identical to the difference in char
s between c[3]
and c[0]
- you get the same result for both.
The arithmetics for pointers subtraction operation is something like:
type* p1 = ...
type* p2 = ...
p1 - p2 == (((int)p1) - (int(p2))) / sizeof(type)
这篇关于C中的数组地址减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!