Reputation: 11
typedef struct {
char a[6];
} foo;
printf("%d", (foo*)0 + 7);
Why does this print out 42? How does this syntax work and what is foo* exactly?
Upvotes: 0
Views: 110
Reputation: 161
Maybe I don't understand what you are asking but this might help.
typedef struct {
char a[6] {7};
} foo;
foo myFoo; // instanciate a foo object
printf("%d\n", (myFoo.a[0]) + 7); // access the first element of the array in foo
printf("%d\n", *myFoo.a + 7); // access the value of the first element's
// address in the array
Upvotes: 0
Reputation: 50775
This is the version of your program that compiles:
#include <stdio.h>
typedef struct {
char a[6];
} foo;
int main()
{
printf("%d", (foo*)0 + 7);
}
The output if 42 because the size of the foo
structure is 6. The expression (foo*)0 + 7
(or its equivalent &((foo*)0)[7]
) denotes therefore address 42 (0 + 6 * 7).
But actually printf("%d", (foo*)0 + 7);
is undefined behaviour (even though the output will most likely be 42
on most platforms), because for printing pointer values (an address is a pointer value) you need the %p
format specifier and you need to cast to void*
(the C standard says so).
So it should be:
printf("%p", (void*)((foo*)0 + 7));
but then it won't print anymore 42
but something like 0000002a
which is 42 in hexadecimal.
Upvotes: 10