首页 > 解决方案 > 如何在 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

标签: c++arrays

解决方案


如果不想初始化整个数组,可以使用 memset 或类似的函数。

#include <string.h>

...
memset(&buf[8], 0, 4);

根据评论,我添加了一种更像 c++ 的方式来做同样的事情:

#include <algorithm>
...
 std::fill(&a[8],&a[8+4],0);

推荐阅读