迷糊中指针减法 [英] Confused in pointer subtraction

查看:86
本文介绍了迷糊中指针减法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #包括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)。 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 be 5 according to Pointer subtraction confusion

What about the second printf statement, what will be the output?

解决方案

To quote C11, chapter §6.5.6, Additive operators

When 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 and ptr2 are pointers to int, hence they are giving the difference in subscript, 5. In other words, the difference of the address is counted in reference to the sizeof(<type>).

OTOH,

 printf("Number of bytes between two pointers are: %d",  
                          (char*)ptr2 - (char*) ptr1);

both ptr1 and ptr2 are casted to a pointer to char, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆