tags:

views:

138

answers:

1

I have a library which expects a array and fills it. I would like to use a std::vector instead of using an array. So instead of

int array[256];
object->getArray(array);

I would like to do:

std::vector<int> array;
object->getArray(array);

But I can't find a way to do it. Is there any chance to use std::vector for this?

Thanks for reading!

+8  A: 

Yes:

std::vector<int> array(256); // resize the buffer to 256 ints
object->getArray(&array[0]); // pass address of that buffer

Elements in a vector are guaranteed to be contiguous, like an array.

GMan
Works :) Thank you!!
But be careful with zero size arrays.
ybungalobill
What if vector gets relocated?
alxx
@alxx: How can it be reallocated from within `getArray`? I assume that's what you mean, since it's not a problem outside of it.
GMan
@alxx: if reallocated, as if `array` was reseated (in the event it's not allocated on the stack) then the pointer would now be invalid. @GMan: I would suggest passing the size, even though it's absent from the original question.
Matthieu M.
@Matthieu: Yeah, exercise for the reader. :)
GMan
Be reminded that this only works for std::vector<T> with T!=bool as std::vector<bool> is a special case, where 8 bools are squeezed into one byte.
fschmitt
@fschmitt: good point, SO unfortunate too :/
Matthieu M.