The first one only works by accident. Change that 2
to a 3
and watch what happens.
size_t block_size = sizeof(block) / sizeof(block[0]); //block_size = 2
Since block
is an int *
and block[0]
is an int
, this gives the ratio of the size of a pointer to an integer to the size of an integer. This happens to be two on your platform. I'd guess your integers are 32-bits and your pointers are 64-bits.
size_t block_size = sizeof(block) / sizeof(block[0]); // block_size = 1
Since block
is now an int**
, this gives the ratio of the size of a pointer to a pointer to an integer to the size of a pointer to an integer. Likely on your platform all pointers are the same size.
If you want to know the size of a block you allocated, you have to keep track of it. The sizeof
operator doesn't do what you think it does -- it tells you the sizes of types, not blocks of memory.