0

#include<bits/stdc++.h>
using namespace std;
int main(){

    float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5};
    float *ptr1 = &arr[0];
    float *ptr2 = ptr1 + 3;
    cout<<*ptr2<<" ";
    cout<<ptr2 - ptr1;

    return 0;
}


Correct output of this code is -> 90.5 3

But I am unable to get the concept behind it. please if anybody can explain how we got this output.

  • Works [here](https://onlinegdb.com/-gKpPlGP6) – Jason Aug 04 '22 at 04:56
  • Does this answer your question? [Pointer Arithmetic](https://stackoverflow.com/questions/394767/pointer-arithmetic) – gstukelj Aug 04 '22 at 04:56
  • 1
    `ptr1` points at `arr[0]` since you initialised it that way. `ptr2` points at `arr[3]` since you initialised it with the value `ptr1 + 3` which is equivalent to `&arr[0 + 3]`. This is because pointer arithmetic takes account of what the pointer points at. So the difference between `ptr2` and `ptr` is measured in number of `float`s, not number of characters. – Peter Aug 04 '22 at 05:00
  • One thing you could try is to change `float *ptr2 = ptr1 + 3;` to `float *ptr2 = ptr1 + 2;` or `float *ptr2 = ptr1 + 4;` and see what difference it makes. – john Aug 04 '22 at 05:30

0 Answers0