简体   繁体   中英

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?

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.

You must be doing something wrong. This works:

#include <QVector>
#include <QDebug>

int main()
{
    QVector<double> v;
    v.append(2.0);
    v.append(18.4);

    double* val1 = &v[0];
    double* val2 = &v[1];

    qDebug() << *val1 << "\n" << *val2 << "\n";
}

Reasons for things going wrong are:

  • vector is reallocated (resized+moved to another position in memory)
  • elements are removed from the vector.
  • output is done incorrectly, or you're printing memory addresses instead of the values.

You should set size of vector when you initialize them. Everything will be fine until you change them (push/pop) after that values in ur pointers will be undefined.

There is a possibility that your pointers may have been invalidated between the time you've obtained them, and the time you've actually used them.

This can happen if the QArray is resized (by adding more elements than it can currently accommodate).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM