2

I try to pass vector as a function argument to pointer but compiler always return error.

error: cannot convert 'std::vector' to 'float*' in assignment

When I have passed array in the same way it works perfectly. So what is wrong here? Is it possible to assign vector to pointer?

vector <float> test;

class data {
    float *pointer;
    int size;
  public:
      void init(vector <float> &test, int number);
};

void data::init(vector <float> &test, int number)
{
    size= number;
    pointer = test;
}
0

2 Answers 2

6

If you want a pointer to the array managed by the vector, then that's

pointer = test.data();                       // C++11 or later
pointer = test.empty() ? NULL : &test[0];    // primeval dialects

Beware that this will be invalidated if the vector is destroyed, or reallocates its memory.

Sign up to request clarification or add additional context in comments.

6 Comments

I would say std::addressof to manage operator & in the old case but it is also C++11 (yes, I know, it is not a problem with float)...
The "primeval" version needs a check for empty.
@DonReba: Good point. I'm glad I don't live in the past.
test.data() works and it seems that I don't have problem with reallocation. But is it possible to say exactly don't destroy this vector before I destroy vector by test.clear()?
@astrak: Just to be clear, destruction isn't the only potential issue. If the vector grows, that will also invalidate your pointer.
|
1

Since C++11, you may use std::vector::data

void data::init(std::vector<float> &test, int number)
{
    size = number;
    pointer = test.data();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.