godzsa
godzsa

Reputation: 2395

Can I cast std::vector<int>* to int*?

Let's say I have a std::vector<int>* foo; and I have to use it as int* (array of int, not pointer to an int) for an old C type library PVM. As far as I am concerned this might work since the vector stores it's elements next to each other in memory just like arrays. So I tried (int*)foo, but somehow I get an error which I'm unable to debug, so I think this must be the problem. Any ideas, thoughts, elegant workarounds?

Upvotes: 2

Views: 10011

Answers (2)

ApproachingDarknessFish
ApproachingDarknessFish

Reputation: 14313

You can't cast the vector directly to an array because the vector object consists of pointers to the array data, not the array data itself, which is dynamically allocated. To access the underlying array, use the data() member function:

std::vector<int> vec;

int *arr = vec.data();

Or

std::vector<int> *vecp = new std::vector<int>;

int *arr = vecp->data();

Upvotes: 10

Tas
Tas

Reputation: 7111

Yes you can. You should prefer this answer by @ApproachingDarknessFish for using std::vector::data which was introduced in C++11.

However, if you are using an older version of C++ you can just use &foo[0] to get an int* to the start of the container.

See this question for why std::vector::data is preferred over &foo.front() and &foo[0] (both which will produce undefined behaviour if foo is empty!)

Have a look at this this answer regarding the contiguous layout of std::vector memory which references the standard:

23.2.6 Class template vector [vector]

1 A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

Upvotes: 4

Related Questions