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