Using vector::data() chaining with member function print differnet values as pointer arithmetic

  c++

I have a class hello with a method which returns a vector member.

I am trying to print out values using vector::data() with pointer arithmetic, but I am facing an undefined behavior. See example below:

class hello
{
public:
    std::vector<int> data()
    {
        return v;
    }

private:
    std::vector<int> v{1, 2, 3, 4};
};

int main(int argc, const char **argv)
{
    hello h;

    std::cout << "----------------------------" << std::endl;
    for (int i = 0; i < 4; i++)
    {
        std::cout << &*(h.data().data() + i) << std::endl;
        std::cout << *(h.data().data() + i) << std::endl;
    }

    int *sa = h.data().data();
    std::cout << "----------------------------" << std::endl;

    for (int i = 0; i < 4; i++)
    {

        std::cout << sa + i << std::endl;
        std::cout << *(sa + i) << std::endl;
    }

    return 0;
}

The result looks like this:

----------------------------
0x9e2ee0
1
0x9e2ee4
2
0x9e2ee8
3
0x9e2eec
4
----------------------------
0x9e2ee0
0
0x9e2ee4
0
0x9e2ee8
10289168
0x9e2eec
0

Why do *(sa + i) and *(h.data().data() + i) print different values?


sa + i and &*(h.data().data() + i) prints the same memory address, why I can not get the correct data just use this memory address (sa + i)

Source: Windows Questions C++

LEAVE A COMMENT