c++arraysstdarray

C++: std::array invalid array assignment


I have the below code. What am I doing wrong that I can't simple assign the array myBar to the 1st index of foo? Using memcpy works but somehow I don't want to use this approach.

#include <array>
#include <string.h>
#include <stdio.h>
    
using bar = struct bar
{
    int  x;
    char y;
};
    
auto main() -> int
{
    std::array<bar [3], 4> foo;
    
    bar myBar [3] = { { 1, 'a'}, { 2, 'b'}, {3, 'c'} };
    
    //  Compiler error "Invalid array assigment" - comment it to get an executable file.
    foo [0] = myBar; 
    
    // This works and foo [0] has also the correct content
    memcpy( foo [0], myBar, sizeof(myBar) );
        
    for ( auto const & fooBar : foo [0] ) {
        printf( "x=%d - y=%c\n", fooBar.x, fooBar.y );
    }
    
    return 0;
}

Full working MRE:
https://onlinegdb.com/fdMYwcFNus


Solution

  • foo [0] = myBar; generates a compilation error because C arrays are non-assignable:
    If you have 2 C arrays - x and y, you cannot use x = y;.
    And in your case foo[0] and myBar are C arrays (not std::arrays).

    A solution would be to use std::array consistently (which is recommended anyway), without mixing with C arrays:

    #include <array>
    #include <iostream>
    
    struct bar {
        int  x;
        char y;
    };
    
    auto main() -> int {
        std::array<std::array<bar, 3>, 4> foo;
        std::array<bar, 3> myBar = { bar{ 1, 'a'}, bar{ 2, 'b'}, bar{3, 'c'} };
        foo[0] = myBar;
        for (auto const& fooBar : foo[0]) {
            std::cout << "x=" << fooBar.x << " - y=" << fooBar.y << "\n";
        }
    }
    

    Output:

    x=1 - y=a
    x=2 - y=b
    x=3 - y=c
    

    Live demo

    Notes:

    1. As you can see above, there's no need for a using statement (in C++, struct bar {...} is already a type).
    2. I used the recommended C++ I/O instead of C's printf (from C++23, there is even a better alternative - std::print).