Search code examples
c++cmemorystructmemcpy

C/C++ fill struct array with one value


I'd like to fill array of MyStruct with same value. How can it be done in fastest and simplest way? I'm operating on rather low-level methods, like memset or memcpy.

edit: std::fill_n indeed complies and works fine. But it's C++ way. How can it be done in pure C?

struct MyStruct
{
    int a;
    int b;
};

void foo()
{
    MyStruct abc;
    abc.a = 123;
    abc.b = 321;

    MyStruct arr[100];
    // fill 100 MyStruct's with copy of abc
    std::fill_n(arr, 100, abc); // working C++ way

    // or maybe loop of memcpy? But is it efficient?
    for (int i = 0; i < 100; i++)
        memcpy(arr[i],abc,sizeof(MyStruct));
}

Solution

  • Be careful to type names of your types correctly (it's case sensitive) and don't forget the semicolon after the definition of your struct, apart from these, your program should compile with no problems:

    #include <iostream>
    #include <algorithm>
    
    struct MyStruct
    {
        int a;
        int b;
    }; // <------------- HERE
    
    int main() {
        MyStruct abc;
        abc.a = 123;
        abc.b = 321;
    
        MyStruct arr[100];
        std::fill_n(arr, 100, abc);
    
        std::cout << arr[99].b;
    }
    

    outputs 321.


    "How can it be done in fastest and simplest way?"

    The simplest way would probably be using std::vector and its appropriate constructor instead:

    #include <vector>
    
    void foo()
    {
        MyStruct abc;
        abc.a = 123;
        abc.b = 321;
    
        std::vector<MyStruct> vec(100, abc);
        ...
    }