c++arraysmemorystructmemset

use memset for array of struct in C++


Well, I want a function like memset but for struct, so that it can be used on some or all elements, like this:

// create array of person data elements
struct {
  unsigned char name[25];
  unsigned char age;
  unsigned int numberPhone;
} persons [256];

// the 256 people have the same name
memset(person, { "Mohammed", 0, 0 } ,sizeof(persons) / sizeof(persons[0]));

I can use a for loop, but I'd prefer to use memset, because it's more performant then for loop in this case.


Solution

  • You can't use std::memset for this. std::memset sets all bytes in a memory area to the same value:

    void* memset( void* dest, int ch, std::size_t count );

    Copies the value static_cast<unsigned char>(ch) into each of the first count characters of the object pointed to by dest.

    If all your 256 objects should be initialized with the same values, just default them:

    struct {
        unsigned char name[25] = "Mohammed";
        unsigned char age = 0;
        unsigned int numberPhone = 0;
    } persons [256];
    

    Nothing more is needed.

    If you don't want default values, create one instance and then std::fill the array:

    #include <algorithm>    // fill
    #include <iostream>
    #include <iterator>     // begin, end
    #include <type_traits>  // remove_reference
    
    int main() {
        struct {
            unsigned char name[25];
            unsigned char age;
            unsigned int numberPhone;
        } persons[256];
    
        // an instance with the proper values:
        std::remove_reference_t<decltype(persons[0])> temp{
            .name = "Mohammed", .age = 0, .numberPhone = 0};
    
        // fill the array
        std::fill(std::begin(persons), std::end(persons), temp);
    }
    

    Note: std::remove_reference_t<decltype(persons[0])> is a cumbersome way to get the type of your anonymous class. Prefer to name the types you create.