Hi,
I have the following struct, where I need a dynamic char array in it.
I allocate memory for the dynamic array, fill the struct and put the whole thing into a QByteArray.
This QByteArray will be used later to get back this struct and access the struct content.
While converting to QByteArray and back I detected something what confused me.
Maybe you can help me.
struct test{
int value_a;
unsigned short value_b;
char *c;
};
struct test{
int value_a;
unsigned short value_b;
char *c;
};
To copy to clipboard, switch view to plain text mode
test *ptr = new test; //creating a new instance
ptr->value_a = 5; //filling the struct instance -----begin
ptr->value_b = 12;
ptr->c = new char[2 * sizeof(char)];
ptr->c[0] = 'A';
ptr->c[1] = 'B'; //filling ----------------------------end
char *p = (char*)ptr; //need to cast it to char* to make a QByteArray
QByteArray bytearray
(p,
4+ 2 + 2 * sizeof(char));
// 4bytes (integer) + 2bytes (unsigned short) + 2bytes (char array with 'A' and 'B')
test *xy = (test*)bytearray.data(); // now getting back the data from QbyteArray
int p = xy->a;
unsigned short q = xy->b;
char r[2];
memcpy(&r,xy->c,2); // copy the original array with 'A' and 'B' to r[2]
test *ptr = new test; //creating a new instance
ptr->value_a = 5; //filling the struct instance -----begin
ptr->value_b = 12;
ptr->c = new char[2 * sizeof(char)];
ptr->c[0] = 'A';
ptr->c[1] = 'B'; //filling ----------------------------end
char *p = (char*)ptr; //need to cast it to char* to make a QByteArray
QByteArray bytearray(p, 4+ 2 + 2 * sizeof(char)); // 4bytes (integer) + 2bytes (unsigned short) + 2bytes (char array with 'A' and 'B')
test *xy = (test*)bytearray.data(); // now getting back the data from QbyteArray
int p = xy->a;
unsigned short q = xy->b;
char r[2];
memcpy(&r,xy->c,2); // copy the original array with 'A' and 'B' to r[2]
To copy to clipboard, switch view to plain text mode
When I try to access here xy->c (the array), I get an invalid pointer.
Can't access it, so memcpy fails.
So now the confusing thing:
When I increase the dynamic array size to 3 like this:
ptr->c = new char[3 * sizeof(char)];
ptr->c[0] = 'A';
ptr->c[1] = 'B';
ptr->c[2] = 'C';
ptr->c = new char[3 * sizeof(char)];
ptr->c[0] = 'A';
ptr->c[1] = 'B';
ptr->c[2] = 'C';
To copy to clipboard, switch view to plain text mode
And also change other places from "2 * sizeof(char)" to "3 * sizeof(char)"
It WORKS!!!
But why not with an array of 2 bytes?


Bookmarks