[Solved] How this is calculating size in c?


First and foremost, please don’t write code this way… *(&arr + 1) is undefined behavior


Note: This answer assumes sizeof(int) = 4.

What is arr? It’s an array of 9 ints

printf("%zu\n", sizeof(arr)); // 36 bytes
printf("%p\n", (void *)arr); // 0x7ffed90f48a0

What is &arr? It’s a pointer to an array or ints = int (*)[9]

printf("%zu\n", sizeof(&arr)); // 8 bytes (the size of a pointer)
printf("%p\n", (void *)(&arr)); // 0x7ffed90f48a0

What is &arr + 1? Since this implies pointer arithmetic, the result is a pointer to the subsequent int (*)[9] in the memory (Notice the address gap of 0x24(36) bytes)

printf("%zu\n", sizeof(&arr + 1)); // 8 bytes (the size of a pointer)
printf("%p\n", (void *)(&arr + 1)); // 0x7ffed90f48c4

What is *(&arr + 1)? We dereference the pointer to the subsequent array &arr + 1 and get a pointer to an array of ints, just like our original arr, only that this pointer points to some invalid memory location:

printf("%zu\n", sizeof(*(&arr + 1))); // 36 bytes
printf("%p\n", (void *)(*(&arr + 1))); // 0x7ffed90f48c4

Conclusion

*(&arr + 1) - arr performs an implicit pointer arithmetic subtraction between two int arrays (pretty much the same as subtracting int *).

Since we already saw that the difference is 36 bytes, and we use int units and sizeof(int) = 4, the result is 9.

7

solved How this is calculating size in c?