I was trying a program to understand the behavior of structure variable,
Sample code:
struct temp
{
int a;
int b;
}obj;
int main()
{
obj.a = 10;
obj.b = 7;
/* to see whether obj and &obj both are same
* I was verifying whether structure variables behave as arrays
*/
printf("%d -- %p",obj,&obj);
return 0;
}
I was expecting output to be 10 and address of obj
But to my surprise,
Actual output is
10 and 00000007
This is bugging me a lot now!!!
Could anyone please help me understand why printf is taking second member and printing its value.
This happens because the first parameter is expected to have 4 bytes (an int) but it has 8 bytes (struct obj).
When you pass obj to printf function it will place on the stack the whole obj structure (including b member). So when printing it will take the first 4 bytes on the stack for 1st parameter (obj.a) and the next 4 bytes on the stack (obj.b) for 2nd parameter.
Check this out: