Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the pointer the continous memory fragment in a std::vector<char> in C++?

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.

like image 907
bodacydo Avatar asked Dec 23 '22 00:12

bodacydo


2 Answers

The standard way to access the vector data is to use

&data[0]
like image 86
stefaanv Avatar answered May 18 '23 21:05

stefaanv


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.

like image 40
paercebal Avatar answered May 18 '23 20:05

paercebal