+ 1

Why exactly 6?

#include <iostream> struct Example{ int a, b; }; int main() { Example e = {9, 6}; int* y = (int*)((char*)&e + 4); std::cout << y[0]; return 0; } Outputs 6, do you know why?

30th Aug 2018, 1:40 PM
Oleg Storm
Oleg Storm - avatar
4 ответов
+ 2
The struct in memory takes 8 bytes, because there are two ints with 4 bytes next to each other. In this case they have values 9 and 6 &e points to the beginning of the struct char has 1 byte, so after casting &e to char* and increasing by 4 it is moves 4 bytes forward then you cast it back to int* and output the int, so you output the second 4 bytes, which have value 6
30th Aug 2018, 1:53 PM
michal
+ 3
According to the standard draft (n4296) §3.11 P.80 " Object types have alignment requirements [...] which place restrictions on the addresses at which an object of that type may be allocated. An alignment is an [ implementation-defined ] integer value representing the number of bytes between successive addresses at which a given object can be allocated. [...] " As respect to the above requirement , since the object alignment is an implementation-defined factor, the OP's code needs to specify that while doing pointer arithmetic. In addition, since all data members are integer, casting the base address to char* is needlessly awkward to consider and also leads to logical error if done carelessly. So, as far as the portability is concerned, the above code can be written as below struct Example{ int a, b, c; }; int main() { Example e = {9, 6, 5}; size_t dist = alignof(e) / sizeof(int); int* y = ((int *)&e + 1 * dist); std::cout << y[0]; }
30th Aug 2018, 4:51 PM
Babak
Babak - avatar
+ 2
michal this is what exactly I thought..but was confused with char* typecast.. why it doesn't work i.e. print second element value that is 6 if I typecast to int* instead of char* char* and int* both are pointer and asaik, both pointer occupies same memory..int and char may require different memory that I do agree
30th Aug 2018, 2:26 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
Ketan Lalcheta char is 1 byte, int is 4 bytes when there is char*, +4 moves the pointer 4 bytes but when it is int*, +4 moves the pointer 4*4=16 bytes
30th Aug 2018, 7:38 PM
michal