C++ Pointer to a Vector Syntax

Started by
1 comment, last by Lith 9 years, 10 months ago

Quick question, if I declare this pointer to a vector:


std::vector<int>* myVector = &someOtherVector;

Why does this not work?


*myVector[0] = 42;

And why does this work?


(*myVector)[0] = 42;

Thanks.

Advertisement

*myVector[0] = 42; evaluates to *(myVector[0]) = 42; because operator[] has a higher priority than operator*(). As a result, you're trying to dereference an integer which causes the error.

*myVector[0] = 42; evaluates to *(myVector[0]) = 42; because operator[] has a higher priority than operator*(). As a result, you're trying to dereference an integer which causes the error.

All clear now! Thank you very much.

This topic is closed to new replies.

Advertisement