Pointer arithmetic getting wrong output [duplicate]

懵懂的女人 提交于 2019-11-28 02:05:26

问题


This question already has an answer here:

  • Pointer Arithmetic In C 2 answers

In the following program, Here ptr Has been declared as a pointer to an integer pointer and assigned the base address of the array p[], which has been declared as an array of integer pointer. Suppose ptr contains the address 9016 (suppose the starting address of p is 9016) before ptr is incremented and after ptr++, it will contain the value 9020 (suppose int takes 4 bytes).

So ptr-p should give the output as 4 i.e (9020-9016=4). But it is giving output as 1 . why?

#include<stdio.h>
int main()
{
    static int a[]={0,1,2,3,4};
    static int *p[]={a,a+1,a+2,a+3,a+4};
    int **ptr=p;
    ptr++;
    printf("%d",ptr-p);
    return 0;
}

回答1:


The result of one pointer minus another pointer is the number of elements between them, not the number of bytes.

int **ptr=p;
ptr++;

ptr moves forward one element, so ptr - p has a value of 1.

BTW, this behavior is consistent with ptr++ (which means ptr = p + 1; in your example.




回答2:


Subtraction of a pointer from another pointer of same base type returns an integer,which denotes the number of element of that between the two pointers.

If we have 2 pointer two int pointers p1 and p2, containing addresses 1000 and 1016 respectively, then p2-p1 will give 4 (since size of int 4).




回答3:


When you find the difference between two pointer you will get the number of objects between them. In this case as the objects are of type integer you correctly got the value 1.

If you want to know the value in terms of bytes then you should do:

printf("%d",(char *)ptr-(char *)p);

It will print 4.



来源:https://stackoverflow.com/questions/26157001/pointer-arithmetic-getting-wrong-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!