到底为什么这个结构体的大小是32?

问题描述 投票:0回答:1

我需要帮助来找到下面结构的大小

#include <stdio.h>
struct bottle{
    float* weight;
    int* qnty;
    char* type;
    char* color;
};

int main(){
    printf("%zu\n", sizeof(struct bottle));
    return 0;
}

我得到的输出为 32,但我不明白它是如何用该值导出的,我希望有人解释为什么它是 32。

PS:我使用的是Linux编译器。

c linux struct embedded-linux
1个回答
0
投票

根据提供的结果,我假设您使用的是 64 位计算机。这意味着您的系统很可能具有 64 位地址总线,因此它可以 address 的地址是 64 位宽。

由于 C 指针是内存地址,因此在 64 位机器上任何类型的指针都是 64 位宽。

/* 64 bits = 8 bytes */

struct bottle {
    float *weight; /* 8 bytes */
    int *qnty;     /* 8 bytes */
    char *type;    /* 8 bytes */
    char *color;   /* 8 bytes */
};

/* Grand total: 32 bytes */

在 32 位机器上,这将是 16 个字节。

© www.soinside.com 2019 - 2024. All rights reserved.