Is it possible to get a pointer to a piece of contiguous memory in std :: vector <char> in C ++?

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

I can not write things 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 the data in vectorvia a pointer?

Thanks, Boda Sido.

+3
source share
3 answers

The standard way to access vector data is to use

&data[0]
+8
source

. :

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

p , , , C.

+2

You can write this code completely legally. All you have to do is change fill_data to take std::vector<T>&. Of course, if this is an external C API, then you do not have much choice in this matter.

0
source

Source: https://habr.com/ru/post/1760510/


All Articles