You can also do this, but it assumes your T t
data is not really const as I remove its constness with const_cast<>()
#include <cstdio>
#include <cstring>
#include <algorithm>
struct T {
int a[3];
int b;
int c;
};
int main() {
const int as[3] = { 5, 6, 7, };
const T t {
{0}, 2, 3,
};
memcpy( reinterpret_cast< void* >( const_cast< int* > ( t.a ) ),
reinterpret_cast< const void* >( as ),
std::min( sizeof t.a, sizeof as ) );
printf( "t.a: '%d, %d, %d'\n", t.a[0], t.a[1], t.a[2] );
return 0;
}
If you data T t
is not actually const, you can do it without the const_cast<>()
#include <cstdio>
#include <cstring>
#include <algorithm>
struct T {
int a[3];
int b;
int c;
};
int main() {
const int as[3] = { 5, 6, 7, };
T t {
{0}, 2, 3,
};
memcpy( reinterpret_cast< void* >( t.a ),
reinterpret_cast< const void* >( as ),
std::min( sizeof t.a, sizeof as ) );
printf( "t.a: '%d, %d, %d'\n", t.a[0], t.a[1], t.a[2] );
return 0;
}
I am adding the reinterpret_cast<>()
because memcpy()
requires a void*
function
void * memcpy ( void * destination, const void * source, size_t num );
Copies the values of num bytes from the location pointed to by source directly to the memory block pointed to by destination.
http://www.cplusplus.com/reference/cstring/memcpy/
I am also doing std::min( sizeof t.a, sizeof as )
to avoid override any data it should not in case the source array is way bigger than expected.
And finally, {0}
is initializing by default the destine array with zeros. It could also be {}
to not initialize anything and let the default values to be trash memory/random data.
References:
- When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
- Should I use static_cast or reinterpret_cast when casting a void* to whatever
- When to use reinterpret_cast?
- Should I use a C++ reinterpret_cast over a C-style cast?
- Use of min and max functions in C++