简体   繁体   中英

How does this code in C work?

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM