How to assign value to part of array?



  • For example,

    char *flag = new char [5];
    flag[0] = 0xA;
    flag[1] = 0x2;
    flag[2] = 0x4;
    flag[3] = 0x8;
    flag[4] = 0x9;

    But it is not a good way. Some other way like below could be better. But Qt doesn't support it. Does anyone know how to do similarly? Thanks!

    flag[0..4] = 0x9842A;

    Or just assign value to part of the array, like below. How to do similarly? Thanks!

    flag[1..3] = 0x842;



  • @char flag[] = { 0xA, 0x2, 0x4, 0x8, 0x9 };@

    That is really something that is or is not provided by the language (C++ in this case), not by the application framework.



  • Well, you could always do this:
    [code]for (int i(1); i<4; i++)
    flag[i] = 0x9842A;
    [/code]

    Sure, the sugar is not as nice as what you post, but AFAIK, C++ does not support that, not even in the new upcomming c++0x. Your version is more efficient at runtime though, if your compiler is not smart enough to unroll the loop...

    edit: thanks for the correction, I was a bit distracted. I do know how to write a for loop :-)



  • Andre, looks like you forgot mask for hex value (to assign only one byte at a time).



  • C++0x will allow array initialization lists. I hope it comes out soon.



  • Thank all of you for your comments!

    I tested below program and the result is followed. By this way, it should work as I want.

    @ char flag = new char [5];
    for (int i=1; i<4; i++)
    {
    flag[i] = 0x090804020A>>(i
    8);
    printf("%d, flag=%x\n", i, flag[i]);
    }

    int j=0;
    printf("%d, flag=%x\n", j, flag[j]);
    int k=4;
    printf("%d, flag=%x\n", k, flag[k]);@
    

    Result:

    1, flag=2
    2, flag=4
    3, flag=8
    0, flag=38
    4, flag=78



  • I got what you tried to do, but this way is not efficient in my opinion. Wouldn't that be easier to do with a union?

    @union T
    {
    unsigned long long i;
    char c[5];
    };

    T t;
    t.i = 0x090804020A;
    // ...
    // further work with t.c@



  • That's heavily platform dependend: size of unsigned long long, 32 or 64 bit architecture, compiler, endianess.

    Why not use "QByteArray":http://doc.qt.nokia.com/4.7/qbytearray.html?



  • Hi, please notice that my focus is how to assign value to part of the array and in the same time not influence the rest part of the array.



  • Then these are your friends:

    @
    QByteArray & QByteArray::replace ( int pos, int len, const QByteArray & after );
    QByteArray & QByteArray::replace ( int pos, int len, const char * after, int alen )
    @


Log in to reply
 

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