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.

Qt Code:
  1. struct test{
  2. int value_a;
  3. unsigned short value_b;
  4. char *c;
  5. };
To copy to clipboard, switch view to plain text mode 

Qt Code:
  1. test *ptr = new test; //creating a new instance
  2.  
  3. ptr->value_a = 5; //filling the struct instance -----begin
  4. ptr->value_b = 12;
  5.  
  6. ptr->c = new char[2 * sizeof(char)];
  7. ptr->c[0] = 'A';
  8. ptr->c[1] = 'B'; //filling ----------------------------end
  9.  
  10.  
  11.  
  12. char *p = (char*)ptr; //need to cast it to char* to make a QByteArray
  13.  
  14. QByteArray bytearray(p, 4+ 2 + 2 * sizeof(char)); // 4bytes (integer) + 2bytes (unsigned short) + 2bytes (char array with 'A' and 'B')
  15.  
  16.  
  17.  
  18. test *xy = (test*)bytearray.data(); // now getting back the data from QbyteArray
  19. int p = xy->a;
  20. unsigned short q = xy->b;
  21.  
  22. char r[2];
  23. 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:

Qt Code:
  1. ptr->c = new char[3 * sizeof(char)];
  2. ptr->c[0] = 'A';
  3. ptr->c[1] = 'B';
  4. 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?