-3

Also following this topic: What does "dereferencing" a pointer mean?

assert(p[1] == 'b');

the operator [] should automatically deference the pointer, let me direct "change" the value to the pointed data.

But if I do somethings like this:

void QuadraticInterpolateArray(vector<double> *b) {

    // ...

    double step = 12.2;
    for (int j = 0; j < (*b).size(); j++) {
        b[j] = step;
    }

    // ...
}

I can't use b[j] = step; i.e. I'm trying to set 12.2 at each index of the vector.

Where am I wrong? What's different?

Community
  • 1
  • 1
markzzz
  • 47,390
  • 120
  • 299
  • 507

2 Answers2

4

std::vector::operator[] dereferences a pointer to the beginning of vector's internal array added with the offset. You added another indirection level yourself, so you have to do (*b)[j] to call operator[] on std::vector.

b[j] however, calls operator[] on std::vector*, which gives you std::vector (valid only for j = 0 if b does not point to an array). You can't assign double to std::vector<double> like that.

And yes, you should use reference for the parameter instead, which lets you use the same syntax as with values, but with changes to the passed vector as with pointers.

void QuadraticInterpolateArray(vector<double> &b) {
    // TODO: use std::fill
    double step = 12.2;
    for (int j = 0; j < b.size(); j++) {
        b[j] = step;
    }
}
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
1

In order to access each element of the vector through pointer to that vector you have to first get the vector value by dereferencing the pointer to it, and then you can use operator [] on that vector to access its elements:

(*b)[i] = step;
Ganil
  • 519
  • 5
  • 13