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;
}
astrak
  • 205
  • 1
  • 3
  • 9

2 Answers2

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 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`)... – Jarod42 Sep 10 '14 at 16:51
  • 1
    The "primeval" version needs a check for empty. – Don Reba Sep 10 '14 at 16:53
  • 3
    @DonReba: Good point. I'm glad I don't live in the past. – Mike Seymour Sep 10 '14 at 16:54
  • 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 Sep 10 '14 at 16:59
  • @astrak: Just to be clear, destruction isn't the only potential issue. If the vector grows, that will also invalidate your pointer. – Fred Larson Sep 10 '14 at 17:01
  • @FredLarson Yes, I know. But it was a good point. There is always problem with that when I need something like vectors between functions. I tried to solve it by putting vector to the global scope but I think it could be deleted anyway. – astrak Sep 10 '14 at 17:06
1

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

void data::init(std::vector<float> &test, int number)
{
    size = number;
    pointer = test.data();
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302