我想用 0 初始化 char 数组的最后 4 个字节(将所有 32 位设置为零)。但是赋值只改变了数组中的一个字节。如何在单个命令中更改此字节和接下来的三个字节,而不是遍历所有 4 个字节?这可能吗?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
char buf[8 + 4]; // 8 bytes of garbage + 4 = 32 safety bits
buf[8] = (uint32_t)0; // turns all safety bits into zero???
cout << hex << setfill(' ');
for (int i=0; i<8 + 4; i++) {
cout << setw(3) << (int)buf[i];
}
cout << dec << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
那是显示:
0 9 40 0 0 0 0 0 0 8 40 0
^ ^ ^ ^
ok garbage undesired
Run Code Online (Sandbox Code Playgroud)
如果不想初始化整个数组,可以使用 memset 或类似函数。
#include <string.h>
...
memset(&buf[8], 0, 4);
Run Code Online (Sandbox Code Playgroud)
根据评论,我添加了一种更像 c++ 的方法来做同样的事情:
#include <algorithm>
...
std::fill(&a[8],&a[8+4],0);
Run Code Online (Sandbox Code Playgroud)