C++ 字节数组赋值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2240405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:40:17  来源:igfitidea点击:

byte array assignment

c++

提问by djones2010

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

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

the above code is giving me an error expected primary-expression before ']' token. can anyone tell me whats wrong with this type of assignment?

上面的代码在']'标记之前给了我一个错误预期的primary-expression。谁能告诉我这种类型的作业有什么问题?

回答by UncleBens

Arrays cannot be assigned. You can only initializethem with the braces.

无法分配数组。你只能用大括号初始化它们。

The closest you can get, if you want to "assign" it later, is declaring another array and copying that:

如果您想稍后“分配”它,您可以获得的最接近的是声明另一个数组并复制它:

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:

或使用 std::tr1 或 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';
    }
}

回答by EvilTeach

What Ben and Chris are saying is.

本和克里斯所说的是。

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

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

如果你想在运行时做,你可以使用 memcpy 来完成这项工作。

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

memcpy(test, startState, sizeof(test));

回答by Void

In addition to @Chris Lutz's correct answer:

除了@Chris Lutz的正确答案:

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

Note that you don't need to explicitly specify the array size in this case unless you want the array length to be larger than the number of elements between the brackets.

请注意,在这种情况下,您不需要显式指定数组大小,除非您希望数组长度大于括号之间的元素数。

This only works if you're initializing the array when it is declared. Otherwise you'll have to initialize each array element explicitly using your favorite technique (loop, STL algorithm, etc).

这仅适用于在声明数组时对其进行初始化的情况。否则,您必须使用您喜欢的技术(循环、STL 算法等)显式初始化每个数组元素。

回答by Chris Lutz

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

除了@UncleBens的正确答案之外,我还想说明这一点:

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

Can be shortened to:

可以缩短为:

byte test[4] = { 0 };

This is the initialization syntax that you're trying to use. The language will fill up un-assigned spaces with 0, so you don't have to write { 0, 0, 0, 0 }(and so that, if your array length changes later, you don't have to add more).

这是您尝试使用的初始化语法。该语言将用 0 填充未分配的空格,因此您不必编写{ 0, 0, 0, 0 }(因此,如果您的数组长度稍后更改,则不必添加更多)。