C/C++ fill struct array with one value

11,421

Solution 1

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);
    ...
}

Solution 2

for(int i = 0; i < 100; i++)
{
    arr[i] = abc;
}

Fastest and cleanest. The optimizer will most likely work it's magic too.

Solution 3

The following should work in C

MyStruct arr[100] = {
   {123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
   {123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
   {123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
   {123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
   {123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
   {123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
   {123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
   {123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
   {123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},
   {123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321},{123,321}};
Share:
11,421
Greg Witczak
Author by

Greg Witczak

Updated on June 04, 2022

Comments

  • Greg Witczak
    Greg Witczak almost 2 years

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