I’m trying to read an array of unsigned shorts using the Qt API. Unfortunately, I’m not getting the desired results.
The following code
QFile in(fileName);
int len = in.size();
QDataStream d(&in);
quint16 *data = new quint16[len];
qDebug() << data[0];
qDebug() << data[1];
d >> data[0];
qDebug() << data[0];
qDebug() << data[1];
outputs
52685
52685
13109
52685
Implying that the data is only changed at the first array position. Also, I always thought that arrays are zero initialized? Using a QByteArray doesn’t seem to work here, that’s why I’m trying to use a array of quint16 (= unsigned shorts). Using a loop may be an option, but I’m trying to avoid a costly loop where ever possible.
So, how do fill said array (data) with the desired data from the file? Is it possible to carry the data using a QByteArray?
First of all,
in.size()returns the size of the file in bytes, and since you are using unsigned shorts (which are 2 bytes each), the size of your data array should belen/2.Also, QDataStream is provided for serialization purposes. This means that it is mainly useful for extracting single objects at a time. See the documentation for QDataStrean for more information.
You can extract the whole array without loops or copying with this code:
If you only wish to read data but never modify it, you can make your program a lot faster by changing the last line to:
Keep in mind however that with this (somewhat ugly) code the pointer will only be valid for the lifetime of the QByteArray object. This usually means that you can only use
datauntil the end of the function.If you wish your data to persist longer than that, you must allocate the array and read directly into it:
This way, you can access the data until you
delete[] data.Finally, to answer your subquestion, arrays are zero-initialized only if they are globally defined (and you shouldn’t rely even on this). Arrays allocated with
newormallocare never zero-initialized for performance reasons.