Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get std::vector pointer to the raw data?

Tags:

c++

stl

vector

People also ask

How do you assign a pointer to a vector in C++?

To assign a pointer to 'point to' an instance of an object use pointer = &vector_of_reviews . The & operator gets the address of something, and it's this that you want to assign to the pointer. *pointer = vector_of_reviews dereferences the pointer (obtains the actual object 'pointed to').

Is std::vector a pointer?

std::vector is a sequence container that encapsulates dynamic size arrays. So definately, it is not a pointer.

How is a std::vector stored in memory?

Vectors are assigned memory in blocks of contiguous locations. When the memory allocated for the vector falls short of storing new elements, a new memory block is allocated to vector and all elements are copied from the old location to the new location.


&something gives you the address of the std::vector object, not the address of the data it holds. &something.begin() gives you the address of the iterator returned by begin() (as the compiler warns, this is not technically allowed because something.begin() is an rvalue expression, so its address cannot be taken).

Assuming the container has at least one element in it, you need to get the address of the initial element of the container, which you can get via

  • &something[0] or &something.front() (the address of the element at index 0), or

  • &*something.begin() (the address of the element pointed to by the iterator returned by begin()).

In C++11, a new member function was added to std::vector: data(). This member function returns the address of the initial element in the container, just like &something.front(). The advantage of this member function is that it is okay to call it even if the container is empty.


something.data() will return a pointer to the data space of the vector.


Take a pointer to the first element instead:

process_data (&something [0]);