迷糊中指针减法 [英] Confused in pointer subtraction
问题描述
#包括LT&;&stdio.h中GT;
诠释的main()
{
INT ARR [] = {10,20,30,40,50,60};
为int * ptr1的ARR =;
为int * PTR2 =编曲+ 5;
的printf(两指针之间的元素个数是:%D,
(PTR2 - ptr1的));
的printf(两个指针之间的字节数数:%d,
(字符*)PTR2 - (字符*)ptr1的);
返回0;
}
对于第一个的printf
语句的输出将 5
按Pointer减法混乱
关于第二个printf语句什么,会是怎样的输出?
要报价 C11
,章§6.5.6,加法运算符的
当两个指针相减,两个人都要指向同一个数组对象,或者一个过去的数组对象的最后一个元素的元素;结果是两个数组元素的下标之差
块引用>所以,当你在做
的printf(两指针之间的元素个数是:%D,
(PTR2 - ptr1的));两者
ptr1的
和PTR2
是指向INT
(;类型>&LT)。 ,所以他们给换句话说标,5区别,地址的差额,参照sizeof的计算p>
OTOH,
的printf(两个指针之间的字节数数:%d,
(字符*)PTR2 - (字符*)ptr1的);两者
ptr1的
和PTR2
的铸造的的指针字符
,它的大小为1字节。利息收入的计算需要相应的地方。结果:20
FWIW ,请注意,两个指针减法产生的结果类型
ptrdiff_t的
,你应该使用TD%
格式说明符打印结果。#include<stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr1 = arr; int *ptr2 = arr + 5; printf("Number of elements between two pointer are: %d.", (ptr2 - ptr1)); printf("Number of bytes between two pointers are: %d", (char*)ptr2 - (char*) ptr1); return 0; }
For the first
printf
statement the output will be5
according to Pointer subtraction confusionWhat about the second printf statement, what will be the output?
解决方案To quote
C11
, chapter §6.5.6, Additive operatorsWhen two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.
So, when you're doing
printf("Number of elements between two pointer are: %d.", (ptr2 - ptr1));
both
ptr1
andptr2
are pointers toint
, hence they are giving the difference in subscript, 5. In other words, the difference of the address is counted in reference to thesizeof(<type>)
.OTOH,
printf("Number of bytes between two pointers are: %d", (char*)ptr2 - (char*) ptr1);
both
ptr1
andptr2
are casted to a pointer tochar
, which has a size of 1 byte. The calculation takes place accordingly. Result:20
.FWIW, please note, the subtraction of two pointers produces the result as type of
ptrdiff_t
and you should be using%td
format specifier to print the result.这篇关于迷糊中指针减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!