0

Code:-

#include<iostream>

int main() {
    int arr[] = { 10,20,30,40,50 };
    int* i, * j;
    i = &arr[1];
    std::cout << i<<std::endl;
    j = &arr[3];
    std::cout << j<<std::endl;
    std::cout << j - i << std::endl << *j - *i;
}

Output:-

000000D20EDEF96C
000000D20EDEF974
2
20

On the execution of j - i printf should have printed 8 but instead it prints 2.

Can you explain what's the mystery behind this?

Ravi Arya
  • 9
  • 1
  • 6
  • `printf("%u\n", i);` is wrong, in either language. If you're programming in C use `printf("%p\n", (void *) i);` – Some programmer dude May 16 '22 at 08:48
  • 1
    As for the arithmetic with pointers, it's done in "array" *elements* not in bytes. There is a two-element difference between `i` and `j`, so that's the result you will get. – Some programmer dude May 16 '22 at 08:49
  • I may say something not correct, but it's 2 because i and j are "int pointer", and "j - i" will give you the result not in byte as you seem to expect (8) but in "sizeof(int pointer)" wich is 2 in your case. I'm not sure if I'm clear, I don't have the correct term in english. – Tom's May 16 '22 at 08:50
  • The linked duplicate uses `++` instead of `-` but apart from that it holds the same newbie FAQ misconception. – Lundin May 16 '22 at 08:52
  • @Tom's No that doesn't make sense. It rather gives the difference expressed in the number of items, in the array with `(sizeof arr) / (sizeof *arr)` items. – Lundin May 16 '22 at 08:56
  • @Lundin that's what I had in mind, but maybe I wasn't precise enougth in my explanation. What I wanted to say was akin to " when you do `array++`, you doesn't go to the next Bytes, you go by `sizeof(*array)` Bytes", granted that if you have a char array, then you go to the next Byte. Anyway, Some programmer dude and you say what I wanted to say more clearer, I will try to remember how you said it. – Tom's May 16 '22 at 09:25

0 Answers0