Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to memory block which allocated by std::vector?

Many people recommend vector class for variable length array. And I have to pass pointer to memory block to GL. How can I access pointer to memory block allocated by std::vector?

like image 609
eonil Avatar asked Mar 26 '11 11:03

eonil


People also ask

Where are vectors 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.

How does std::vector allocate memory?

As mentioned above, std::vector is a templated class that represents dynamic arrays. std::vector typically allocates memory on the heap (unless you override this behavior with your own allocator). The std::vector class abstracts memory management, as it grows and shrinks automatically if elements are added or removed.

How is a vector of vectors stored in memory C++?

The elements of a vector are stored in a dynamically allocated block of memory; otherwise, the capacity of the vector could not increase. The vector object just holds a pointer to that block.

Is std::vector contiguous in memory?

Yes, the elements of a std::vector are guaranteed to be contiguous.


2 Answers

Use the address of first element. If your vector is v then &v[0] will work.

like image 131
Boofhead Avatar answered Sep 28 '22 07:09

Boofhead


ContainerType* pData  = &vec.front();
like image 31
Goz Avatar answered Sep 28 '22 07:09

Goz