views:

85

answers:

3

I moved my code to use std::vector<char> instead of char *mem = malloc(...) but now I am facing a problem that I can only access the vector data through operator [] but not via a pointer.

I can't write stuff like:

std::vector<char> data;
fill_data(data);
char *ptr = data;

Before I could do this:

char *data = malloc(100);
fill_data2(data);
char *ptr = data;

Any ideas if it's still possible to access data in a vector via pointer?

Thanks, Boda Cydo.

+5  A: 

The standard way to access the vector data is to use

&data[0]
stefaanv
In the future, C++0x will add a `data()` member to do this slightly more explicitly.
Mike Seymour
But beware reallocation of vector.
Tadeusz Kopec
Does the C++ standard guarantee that the memory is stored in a contiguous block? **EDIT**: Yes, see the Herb Sutter article.
Philipp
@Philipp: yes indeed, simply because `vector` was created with C-compatibility in mind. When C-compatibility isn't mandated, it's best to use `deque` because of its more stringent iterator validity requirement and its better performance (in general).
Matthieu M.
+2  A: 

Of course. The vector was designed for this purpose:

char * p = &(myVector[0]) ;

And now, p points to the first item in the vector, and you can access each item by playing with the pointer, as you would in C.

paercebal
@bodacydo And something to give you more insights: http://herbsutter.com/2008/04/07/cringe-not-vectors-are-guaranteed-to-be-contiguous/
celavek
A: 

You can write that code perfectly legally. All you need to do is alter fill_data to take a std::vector<T>&. Of course, if this is an external C API, then you don't have much choice in the matter.

DeadMG