Linux下C语言结构体指针数组大小从24变16的原因解析
object_directory's size drop from 24 to 16 when removing the trailing 0? Let's break down exactly what's happening here, using your code and output as reference.
First, a key context: you're running this on a 64-bit Linux system—this dictates the size of pointers in your environment, which is the root of the size change.
1. Pointer size in 64-bit Linux
On 64-bit Linux, any pointer type (including const struct point *) is 8 bytes long. You can confirm this from your output: the pointer values like 0XE2BF0778 are 8 hex digits, which equals 64 bits (8 bytes).
2. Original array size calculation
Your initial array definition:
const struct point *object_directory[] = { &SW_VERSN_POINT, &SWMVERSN_POINT, 0 };
This is an array of 3 elements:
- Two valid pointers to your
struct pointconstants - A trailing
0, which gets implicitly converted to aconst struct point *null pointer (often used as a sentinel/terminator for arrays)
Total size = number of elements × size of each element = 3 × 8 bytes = 24 bytes. This matches your first output line: 24 0XF967D778, 0xF967D788.
3. Modified array size calculation
When you remove the trailing 0, the array becomes:
const struct point *object_directory[] = { &SW_VERSN_POINT, &SWMVERSN_POINT };
Now the array only contains 2 pointer elements.
Total size = 2 × 8 bytes = 16 bytes. Which aligns perfectly with your second output: 16 0XF967D778, 0xF967D788.
Quick sanity check of other outputs
Your other print statements confirm the basics:
sizeof(SW_VERSN_POINT.formatbyte1)is 4, which makes sense becauseintis 4 bytes on most 64-bit Linux systems.sizeof(struct point)is 12, which is 3 × 4 bytes (one for eachintmember, no padding needed here since all members are naturally aligned).
内容的提问来源于stack exchange,提问作者beparas

