How to define a QBitArray variable in a struct?



  • I define a struc like below and then i make an array of this structure:

    struct mm{QBitArray bb; int val;};
    mm* vec=new mm [10];

    then i want to set a bit:
    u [7].bb.setBit(3,1);

    I encounter a crash message.
    whats wrong with this definition?


  • Moderators

    Is u the same as vec ?
    Do you set the size of the bit array somewhere? If not then accessing bit 3 of array of size 0 will obviously be undefined behavior (crash in your case).



  • yeah sorry:
    vec [7].bb.setBit(3,1);
    but i cant set the length in the struct!:
    struct mm{QBitArray bb(8); int val;};
    this causes error.
    How do you define a bitarray in a structure?


  • Moderators

    With that syntax you're trying to call a function(a constructor). You can't call a function at a declaration. It's a compile-time construct.

    You have several choices:
    @
    //if your compiler supports c++11 use uniform initialization:
    struct mm{
    QBitArray bb{8};
    int val;
    };

    //if it doesn't you can either define a constructor:
    struct mm{
    mm() : bb(8) {}
    QBitArray bb;
    int val;
    };

    //or just resize the thing later on:
    struct mm{
    QBitArray bb;
    int val;
    };
    //somewhere later:
    mm foo;
    foo.bb.resize(8);
    @



  • Thanks chris
    if we choose your third approach, HOW can i define the structure mm on HEAP and in the form of an ARRAY??
    like:
    mm* foo=new foo [10]; or something like that.


  • Moderators

    new mm, not new foo. Then you would resize each element in a for loop:
    @
    mm* foo = new mm[10];
    for(int i=0; i< 10; ++i)
    foo[i].bb.resize(8);
    @
    But I would favor the first option. the loop is then unnecessary.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.