0

Can anyone explain me how this code results 16843009? How it works?

As I saw in my tests, (int *)&x results 0x61ff1b and as I know that is the address of the first element in the array. and how the result of *(int *)&x is 16843009? Thanks.

#include <iostream>

using namespace std;


int main()
{
    char x[5] = {1, 1, 1, 1, 1};
    cout << *(int *)&x;

   return 0;;
}
4
  • 1
    What are you trying to achieve? Commented May 18, 2019 at 11:50
  • Ps: try printing it as hex value instead Commented May 18, 2019 at 11:51
  • @JVApen I just wanted to understand how it works. Commented May 18, 2019 at 12:06
  • I read that? Why? The first one trying to use this in my code will have to defend herself/himself. Commented May 18, 2019 at 13:42

1 Answer 1

2

If we write 16843009 as binary we get 1000000010000000100000001. Padding that with extra zeros we get: 00000001000000010000000100000001. Every 8 bits (which is a char) has a value of 00000001, which is 1.

&x is a pointer to an array of char (Specifically a char(*)[5]). This is reinterpreted as a pointer to int. On your system, int is probably 4 bytes, and all four of those bytes are seperately set to 1, which means you get an int where every 8 bits are set to 1.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.