0

I'm using union that have 2 members. One's type is QByteArray, other's double. I want to access QByteArray members after changing value of the double array.

I've tried this using with char * (size = 8) and double union members. There was no problem.

 union smt{
        QByteArray qbyte;             
        double *data;
        ~smt(){}    // needs to know which member is active, only possible in union-like class
    };

     smt x={"sometng"};
     double *result =...;  
     memcpy(x.data,result,sizeof (double)); // copy result to x.data

In this code I want to access the values of the QByteArray after changing the data array. Basically I want to get the string values corresponding the double values. If they are sharing the same memory space, theoretically it's possible, right?

However, after changing the data array, I got runtime error, that says the QByteArray "not accessible"

Am I missing something or doing smtg wrong? Please help me

Thank you, in advance

timrau
  • 22,578
  • 4
  • 51
  • 64
zeynepoguz
  • 11
  • 1
  • 2
    1. QByteArray is not trivial, POD type, so what you want is impossible. 2. Reading a value of an union member that was not used for writing a value is undefined behavior: https://stackoverflow.com/questions/943267/is-it-a-good-practice-to-use-unions-in-c – 273K Jun 23 '19 at 20:39
  • 1
    This is all undefined behaviour, I would strungly recommend not using this technique. If you describe the problem you are trying to solve then someone may be able to offer a suggestion – M.M Jun 24 '19 at 00:01
  • 2
    You can use QVariant instead of union – Fabio Jun 24 '19 at 09:39

0 Answers0