How to assign value to part of array?
-
wrote on 19 Oct 2010, 03:24 last edited by
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;
-
wrote on 19 Oct 2010, 05:33 last edited by
@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.
-
wrote on 19 Oct 2010, 07:45 last edited by
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 :-)
-
wrote on 19 Oct 2010, 10:31 last edited by
Andre, looks like you forgot mask for hex value (to assign only one byte at a time).
-
wrote on 21 Oct 2010, 11:52 last edited by
C++0x will allow array initialization lists. I hope it comes out soon.
-
wrote on 3 Nov 2010, 03:42 last edited by
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 -
wrote on 3 Nov 2010, 07:05 last edited by
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@ -
wrote on 3 Nov 2010, 13:00 last edited by
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?
-
wrote on 3 Nov 2010, 13:06 last edited by
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.
-
wrote on 3 Nov 2010, 13:12 last edited by
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 )
@