Can somebody explain the output of the following program:
int main()
{
int i=512;
char *c=(char*)&i;
c[0]=1;
cout<<"i is:"<<i<<endl;
return 0;
}
output is:513
Can somebody explain the output of the following program:
int main()
{
int i=512;
char *c=(char*)&i;
c[0]=1;
cout<<"i is:"<<i<<endl;
return 0;
}
output is:513
The output of your program unspecified. In practice, it depends on the endianness of your platform and the width of the int
type.
Your platform is little-endian. Let's for simplicity assume that int
is 32 bits wide.
512
10 is 0x00000200
in hex. This is stored in memory as
00 02 00 00
Your code modifies the first byte to 01
. This changes the int
to 0x00000201
, which is 513
decimal.
The program exhibits unspecified behaviour, dependent on the architecture of the machine. To predict and reason about the output requires knowledge of the compiler and the target architecture.
Explanation:
int main()
{
/* Creates int equal to 512 */
int i=512;
/* Creates a char pointer, and points this at i */
char *c=(char*)&i;
/* Overwrites the lowest byte of the 4 byte int with 1 */
/* This sets the lowest bit of the int, which adds 1 */
c[0]=1;
/* Displays the updated int */
cout<<"i is:"<<i<<endl;
return 0;
}
Exactly which part of the int gets overwritten depends on the endianness of the platform you're compiling for. Given the final result of 513, your system is clearly little-endian.