Byte Array Assignment

byte test[4]; memset(test,0x00,4); test[]={0xb4,0xaf,0x98,0x1a}; 

the above code gives me the expected primary expression before the “] 'token. can anyone tell me what happened to this type of assignment?

+6
c ++
source share
4 answers

What do Ben and Chris say.

 byte test[4]={0xb4,0xaf,0x98,0x1a}; 

If you want to do this at run time, you can use memcpy to do the job.

 byte startState[4]={0xb4,0xaf,0x98,0x1a}; byte test[4]; memcpy(test, startState, sizeof(test)); 
+8
source share

Arrays cannot be assigned. You can only initialize them with curly braces.

The closest thing you can get is if you want to "assign" it later, declare another array and copy this:

 const int array_size = 4; char a[array_size] = {}; //or {0} in C. char b[array_size] = {0xb4,0xaf,0x98,0x1a}; std::copy(b, b + array_size, a); 

or using the array class from std :: tr1 or boost:

 #include <tr1/array> #include <iostream> int main() { std::tr1::array<char, 4> a = {}; std::tr1::array<char, 4> b = {0xb4,0xaf,0x98,0x1a}; a = b; //those are assignable for (unsigned i = 0; i != a.size(); ++i) { std::cout << a[i] << '\n'; } } 
+14
source share

In addition to @Chris Lutz, the correct answer is:

 byte test[]={0xb4,0xaf,0x98,0x1a}; 

Please note that you do not need to explicitly specify the size of the array in this case, if you do not want the array to be longer than the number of elements between the brackets.

This only works if you initialize the array when it is declared. Otherwise, you will have to initialize each element of the array explicitly using your favorite method (loop, STL algorithm, etc.).

+7
source share

In addition to @UncleBens correct answer, I want to note that this:

 byte test[4]; memset(test,0x00,4); 

Can be shortened to:

 byte test[4] = { 0 }; 

This is the initialization syntax you are trying to use. The language will fill in unwritten spaces 0, so you do not need to write { 0, 0, 0, 0 } (and so that if the length of your array changes later, you do not need to add more).

+4
source share

All Articles