QByteArray copy [Solved]
-
I'm trying to copy some bytes from one QByteArray to another and I'm having trouble getting it to work. This should be simple but somehow...
The compile error is "error: invalid conversion from 'char' to 'const char*' "
@
void Probe::OP_DataReceive(const QByteArray qa)
{
unsigned char i;char * ptr; ptr = (char *)qa.data() + 3; for (i=0; i<15; i++) { MyData.Probe.Name[i] = *ptr++; }
@
The destination QByteArray is set up as follows.
@
struct MyData_ {
struct Probe_{
unsigned char Number;
QByteArray Name[15];
} Probe;
unsigned char ProbeIsPresent;
} extern MyData;
@Thanks,
James -
Hi,
I'm not sure you really understood how QByteArray works.
If you want to copy a part of a QByteArray simply use:
@QByteArray part = originalArray.mid(startingPoing, length)@
In you MyData structure you are declaring an array of QByteArray, are you sure that's what you want ?
-
You are right, I thought I understood but now I'm not sure.
Can you tell me why this doesn't work?
@
for (i=0; i<15; i++)
{
MyData.Probe.Name[i] = *ptr++;
}
@No, you are correct, I did not want an array of "Name". So, in the structure how should I reserve 15 bytes for the name?
Thanks,
James -
MyData.Probe.Name[i] returns the QByteArray at i,
*ptr++ returns the char pointed by ptr and then increments ptr.
-
What is wrong with the = operator for QByteArray?
and as SGalst said, use other special options to only copy parts of the original QByteArray.
BTW the QByteArray is not like a C array. The class itself will allocate or release required memory, so no need to add the size in the struct. Using the [] operators should be done with care! It is easy to have buffer overflows with them! -
@QByteArray Name[15]@
...creates 15 separate QByteArrays. It's an array of QByteArray's.
--
Instead try:
@void foo(const QByteArray &qa)
{
const char* ptr = qa.constData() + 3;QByteArray myByteArray(15);
char *outPos = myByteArray.data();for (i=0; i<15; i++)
{
*outPos++ = *ptr++;
}
}@--
But I think you can also do:
@void foo(const QByteArray &qa)
{
QByteArray myByteArray;
myByteArray = qa.mid(3, 15);
}@ -
MuldeR, based on your code and if Name becomes a simple QByteArray.
wouldn't
@
MyData.Probe.Name = qa.mid(3, 15);
@be cleaner ?
-
Plz add [SOLVED] to the first post!