How can I get the adress to the first element in the array in a string or a vector?
I only know this way: &MyString[0]
Printable View
How can I get the adress to the first element in the array in a string or a vector?
I only know this way: &MyString[0]
I don't recommend using addresses of vectors' or strings' elements - there are other ways to do that. check http://www.sgi.com/tech/stl/Iterators.html
Seconded. If you absolutely have to then I believe you would use something like...Quote:
Originally Posted by hardi
(void*)&strVal[0]
Well, I am making a SDL project, and I am setting the caption of the window with this line:
Where Caption is a string. The function SDL_WM_SetCaption does not wan't a string, but a const char*, so I thought I may convert it. Caption is set to "Wavetest" when I send "Wavetest" as an argument to another function I have.Code:SDL_WM_SetCaption(&Caption[0], NULL);
I see. Have you tried Caption.c_str()?Quote:
Originally Posted by TriKri
Thank you! That was probably what I was looking for. :)
It is actually somewhat common to get the address of an element in a vector, because a vector's memory is guaranteed to be contiguous. This allows the vector to be used with API's expecting a C style array. &myVec[0] is the correct way to do it.
Of course, it is better to use the vector's built-in interface if possible. Also, you must be aware that inserting or erasing from the vector could cause the address to be invalidated.
A string is not guaranteed to be contiguous, so it is not recommended to do the same thing with a string, and c_str() is of course the correct way to get the const char*.