Click here to Skip to main content
14,937,556 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Given a funcition with this prototype
void Func(int* elements, int count);

Is this
vector<int> v;
v.push_back(1);
Func(&*v.begin(), v.size());

safe? Or how should I call Func? In a portable way, I mean. Does vector guarantee the memory layot of my array in some way?
Posted

1 solution

Safe!
It's guaranteed that the elements of a vector are stored contiguously.

http://www.cplusplus.com/reference/stl/vector/



Sorry. I forgot to tell one important thing.
&*v.begin() isn't safe because sometimes the iterator of a vector is not a pointer. Use &*v[0].
   
v2
Comments
goorley 20-Aug-10 7:09am
   
Thank you!
Emilio Garavaglia 21-Aug-10 3:45am
   
Not &*v[0], but &v[0], since v[0] is a reference and you want a pointer. (*v[0] works only if v[0] has a pointer semantic, but with all other result! Otherwise ill not compile).

Also: whatever v.begin() is, *v.begin() is a reference, so &*v.begin() is a pointer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900