c++ - 如何在 C++ 中一次将 4 个字节分配给 char 数组的特定索引
问题描述
我想用 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;
}
那是显示:
0 9 40 0 0 0 0 0 0 8 40 0
^ ^ ^ ^
ok garbage undesired
解决方案
如果不想初始化整个数组,可以使用 memset 或类似的函数。
#include <string.h>
...
memset(&buf[8], 0, 4);
根据评论,我添加了一种更像 c++ 的方式来做同样的事情:
#include <algorithm>
...
std::fill(&a[8],&a[8+4],0);
推荐阅读
- c# - 为什么 LoadLibrary 失败而 DllImportAttribute 工作?
- javascript - 我想在动态 365 crm 中从一种形式重定向到另一种形式
- javascript - 如何修复使用外部按钮在 ajax 重新加载时刷新 dataTable 时显示的数据?
- c++ - 将 uintptr_t 转换为 bool 会多次减慢 SSO 基准
- docker - 如何回答 dockerfile 中的安装问题?
- pandas - Pyspark 数据框到 Pandas 数据框
- javascript - 如何设置在 JS 中创建的段落元素的样式
- java - 三元表达式可以产生空布尔值而没有编译器错误?
- amazon-web-services - 通过 lambda 访问所有 ec2 跨区域
- c# - 将 JSON 反序列化为 SQLite 数据库