Search code examples
c++qtpointersreferencedereference

Using pointers to access elements of a QVector


I have trouble with pointers and references to doubles.

I want to access elements in QVector by names. The vector contains doubles:

QVector<double> properties;
properties.append(28.0);
properties.append(1.0);
properties.append(44.0);
properties.append(0.001);

Now I create pointers to doubles:

double* Amplitude;
double* Frequency;
double* PhaseDifference;
double* Stepsize;

These pointers should provide access to the elements of my vector:

Amplitude = &properties[0];
Frequency = &properties[1];
PhaseDifference = &properties[2];
Stepsize = &properties[3];

In my opinion dereferencing these pointers should give me the correct values, but it doesn't. In this case I got zeros for the first two pointers and the third and fourth were correct.

I tried to use more entries in the vector and the result was that only the last two had the correct values. What is going wrong there?

I create and print the values in the constructor. Printing of the vector gives the right values!

Does anybody have an idea?


Solution

  • Your named pointers are in fact iterators. Iterators can be invalidated. For example, whenever you resize the vector, or insert anything into them, etc. Look up the exact rules of iterator invalidation for your particular vector type, in this case, QVector and see if you've performed any of those iterator invalidating operations prior to printing. Incidentally, dereferencing an invalidated iterator may result in undefined behavior.