简体   繁体   中英

How to assign 4 bytes at once into a specific index of a char array in C++

I want to initialize the last 4 bytes of a char array with 0 (set all 32 bits to zero). But the assignment is changing only one byte in the array. How can I change this byte and the next three in a single command, instead of looping through all 4 bytes? Is this possible?

#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;
}

That's displaying:

  0  9 40  0  0  0  0  0  0  8 40  0
     ^  ^                    ^  ^
   ok garbage              undesired

if you do not want to initialize the whole array, you can use memset or a similar function.

#include <string.h>

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

based on the comments, i added the a more c++like way to do the same:

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

There is also another option:

*(uint32_t*)(&buf[8]) = 0;

Or, more c++ way:

#include <algorithm>

std::fill(buf + 8, buf + 12, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM