-5

enter image description here Shouldn't the answer be 2nd ques?

ptr1 saves the address of arr[0] and ptr2 saves the address of arr[3]. So (ptr2-ptr1) should be ((34(size of float)) -(04)) i.e., subtraction of address not the subtarction of index..

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 3
    Please post code as text, not images. – ChrisMM Aug 22 '23 at 08:58
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Aug 22 '23 at 09:15
  • Arithmetic works as usual; `(a + b) - a == b`. – molbdnilo Aug 22 '23 at 09:40
  • pointer - index yields a pointer. pointer - pointer yields the difference between the pointers. The question is very unclear. – 463035818_is_not_an_ai Aug 22 '23 at 09:49
  • 1
    Note in practice, it is recommended to not write code based on pointer arithmetic at all. Current C++ has enough (zero cost) abstractions to avoid the need to use them. Also it is best not to write code that assumes a certain memory layout, compilers may add padding bytes to increase performance. – Pepijn Kramer Aug 22 '23 at 10:56

1 Answers1

2

You wrote that

float *ptr2 = ptr1 + 3;

So according to the usual arithmetic ptr2 - ptr1 is equal to 3.:)

The same is valid for the pointer arithmetic.

From the C++20 Standard (7.6.6 Additive operators)

5 When two pointer expressions P and Q are subtracted, the type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as std::ptrdiff_t in the header (17.2.4).

(5.2) — Otherwise, if P and Q point to, respectively, array elements i and j of the same array object x, the expression P - Q has the value i − j.

That is after this line of code

float *ptr2 = ptr1 + 3;

the value of the pointer ptr1 is equal to &arr[0] and the value of the pointer ptr2 is equal tp &arr[3]. The difference yields the number of elements of the array between the first and the fourth elements in the array.

To get the value of the difference of two addresses you can write for example

( ptr2 - ptr1 ) * sizeof( float )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335