Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer arithmetic getting wrong output [duplicate]

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;
}
like image 602
Walter Avatar asked Sep 21 '26 18:09

Walter


2 Answers

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.

like image 77
Yu Hao Avatar answered Sep 24 '26 08:09

Yu Hao


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).

like image 24
Anbu.Sankar Avatar answered Sep 24 '26 10:09

Anbu.Sankar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!