Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Simple hex arithmetic not yielding expected results.  (Read 1528 times)

0 Members and 1 Guest are viewing this topic.

intrinsic

  • Newbie
  • *
  • Posts: 26
    • View Profile
    • Email
Simple hex arithmetic not yielding expected results.
« on: December 17, 2016, 08:59:15 am »
I am trying to understand the "contiguous" nature of vectors and where they assign their values in memory.
Can someone please explain why the 2nd cout yields a 1 instead of a 4?

std::vector<int> test = { 2,13,4 };
std::cout << &test[2] << " " << &test[1] << std::endl;
std::cout << &test[2] - &test[1] << std::endl;

An int on my machine is 4 bytes large.
So that means test[2] is 4 bytes away from test[1] in memory.

if I write:
std::cout << (int)&test[2] << " " << (int)&test[1] << std::endl;
std::cout << (int)&test[2] - (int)&test[1] << std::endl;

Then I get 4...
Can someone explain why the first example yields 1?

Thank you.

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: Simple hex arithmetic not yielding expected results.
« Reply #1 on: December 17, 2016, 10:22:25 am »
Think about the opposite operation. When you add a number to a pointer, you add a number of elements, not a number of bytes (ie. "ptr + 1" moves the pointer to the next element, not to the next byte of the first element). From there, it's obvious that subtraction acts the same way. If you subtract two pointers, you get the number of elements between them, not the number of bytes.

And please note that this is the SFML forum, not a general programming / C++ forum. So please try to find a better place for this kind of questions in the future ;)
Laurent Gomila - SFML developer

intrinsic

  • Newbie
  • *
  • Posts: 26
    • View Profile
    • Email
Re: Simple hex arithmetic not yielding expected results.
« Reply #2 on: December 17, 2016, 05:37:06 pm »
Thank you and sorry.