I am new to C++, and I am reading the book "Beginning C++ Through Game Programming", by Michael Dawson (2011). The book is wonderful, it really helped me understand a lot, but there is something I am not understanding fully.
Here is the code snippet:
1 2 3 4 5
|
string* ptrToElement(vector<string>* const pVec, int i
{
//returns address of the string in position i of vector that pVec points to
return &((*pVec)[i]);
}
|
The return statement is what my question is about. I understand what this code means. It essentially says "Return the address of the information stored in position i of the vector pVec points to". I understand what this means, what it does, and how it works, but I thought that the following code would do the same thing:
But it doesn't compile! I do not understand. It seems to me that this statement means "return the pointer to element i of Vec", or something like that. In other words, as I understand things, it seems to me that in the first code snippet, returning the address of a value stored in a variable pointed to would be the same thing as simply returning the pointer to that variable itself, since that's what a pointer is. In other words, since the pointer pVec[i] contains the address of the information stored in that location, wouldn't simply returning pVec[i] (which is a pointer) be the same thing?
Obviously not, but why?
I also tried
But once again, it does not compile.
What is the difference and what am I missing? I hope this question makes sense, I'm sure I sound like an utter newbie! Any help you can give would be great! If I didn't explain my question well, please feel free to ask questions to help me clarify. I want to understand C++ completely! Thanks in advance!