reopened by
875 views

2 Answers

Best answer
3 votes
3 votes

Let's visualize the whole thing : 

$int \hspace{0.1cm}  {^*ptr1}=arr; \rightarrow$ Address of $10$ will be held by $ptr1$

$int \hspace{0.1cm}  {^*ptr2}=arr +5; \rightarrow$ Address of $60$ i.e. $6^{th}$ element will be held by $ptr2 $ i.e. $\{base \hspace{0.1cm} address + 5^{th} \hspace{0.1cm} location\}$ $(arr+5$ numerically equals $arr + sizeof(*arr) \times 5)$

$\text{printf(``Number of elements between two pointer are: %d.",(ptr2 - ptr1));} \rightarrow$ prints "Number of elements between two pointer are:  5" on the screen

$\because[\text{Distance between the position of arr[5] & arr[0]} \hspace{0.1cm} i.e. \hspace{0.1cm} 5\hspace{0.1cm} or \hspace{0.1cm}$ $\dfrac{\text{difference between addresses }}{\text{sizeof data type pointed by that pointer variable }}$

$\qquad \qquad \qquad \qquad \qquad  = \dfrac{(30-10)}{4}$ [∵ $int$ are of $4$ bytes as mentioned in question]

$\qquad \qquad \qquad \qquad \qquad = \dfrac{20}{4} = 5 ]$

$\text{printf(``Number of bytes between two pointers are: %d", (char*)ptr2 - (char*) ptr1);} \rightarrow$ prints "Number of bytes between two pointers are: 20" on the screen

[$\because ptr2$ is type-casted to $char$ pointer & size of character is $1$ byte

Number of bytes between two pointers = $\text{Number of elements between two pointers} \times \dfrac{\text{sizeof(int)}}{\text{sizeof(char)}}$

$\qquad \qquad \qquad \qquad = 5 \times \dfrac{4}{1}$ = $20$]

edited by
2 votes
2 votes

Difference between two pointers gives the number of elements between them. (ptr2-ptr1)/(size of each element)

Related questions

2 votes
2 votes
1 answer
3
0 votes
0 votes
1 answer
4
Psnjit asked Jan 12, 2019
1,162 views
main(){unsigned int i= 255;char *p= &i;int j= *p;printf("%d\n", j);unsigned int k= *p;printf("%d", k);} Both the outputs are -1. I have even tried with - int i = 255(3rd ...