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;
-
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).
-
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>>(i8);
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 -
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.