Problem in pointer

int main()
{
int i=512;
char *c=(char *)&i;
c[0]=1;
printf("%d",i);

return 0;
}

Can anybody clarify me the step by step execution of the above program?
It's missing an #include (<stdio.h> for C, <cstdio> for C++)

int i=512;
1. creates an object of type int called "i" with automatic storage duration
2. initializes that object with the value 512

char *c=(char *)&i;
1. first, creates a nameless pointer to int and initializes it with the address of "i"
2. reinterprets that pointer to int as pointer to char
3. creates an object of type "pointer to char", called "c", with automatic storage duration
4. initializes that object with the value obtained from 2.

c[0]=1;
stores a value of 1 in the first character pointed to by c.

printf("%d",i);
prints 16777728 (on my computer) or 513 (quite likely on yours), or some other value that depends on how the integers are represented in RAM on your platform.
Last edited on
Thanks for your answer.

But still i have confusion in the printf() statement :(
It outputs 513 on my machine and 16777728 on yours!
What does actually happen here?
What does actually happen here?
You're learning how numbers are stored in computer memory.

On my machine, "int" happens to be 4 bytes (it doesn't have to be, it was 2 on many old 16-bit systems, and it is 8 on a few).

My machine (IBM Power7) stores the four bytes in memory in "big-endian" order, the same way we write on paper: 0x12345678 is stored as 0x12, then 0x34, then 0x56, then 0x78. The number 512 (0x200 in hex) is stored as 0x00, then 0x00, then 0x02, then 0x00.

On consumer PCs, numbers are stored in "little-endian" order, backwards: 0x12345678 is stored as 0x78, then 0x56, then 0x34, then 0x12. The number 512 is stored as 0x00, then 0x02, then 0x00, then 0x00.

The command c[0] = 1; above modifies the first byte.

On my computer, i becomes 0x01, then 0x00, then 0x02, then 0x00. That's 0x01000200 in hex, or 16777728 in decimal.

On yours, it becomes 0x01, then 0x02, then 0x00, then 0x00. That's 0x00000201 in hex (remember, backwards), that's 513 in decimal.
Last edited on
Oh great!
It was really very helpful to me :D
Topic archived. No new replies allowed.