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
std::array
with C-array?x = y;
with C arrays). But if you usestd::array
only (which is better anyway, as suggedted above) it will solve your problem asstd::array
s are assignable. See demo.using bar = ...
?printf
-std::print
from C++23, andstd::cout
before that).std::array
orstd::vector
, both of which support assignment the way you expect.