as far as I know integers for example are placed in memory at integer multiples of their size. Can I access a set of bytes starting at non-integer multiple of sizeof(int) via a pointer as an int? The code below seems to work, producing
Size of int: 4
native byte order: LSB
0 127 0 0 0 0 0 0 0 0 0 0
Is it guaranteed, or not? Thanks.
#include <string.h>
#include <iostream>
#include <bit>
using namespace std;
int main()
{
cerr<<"Size of int: "<<sizeof(int)<<endl;
if(std::endian::native == std::endian::little) cerr<<"native byte order: LSB"<<endl;
else cerr<<"native byte order: MSB"<<endl;
const int N = 3;
int array_int[N];
memset(array_int,0,sizeof(int)*N);
std::byte *array_byte = (std::byte*)array_int;
int *ptr = (int*)(array_byte+1);
*ptr = 127;
for(int i=0; i<N*sizeof(int); ++i) cerr<<(int)(array_byte[i])<<" ";
cerr<<endl;
return 0;
}
The above example compiles and runs as expected naively
1