【问题标题】:array of structures - sizeof returning unexpected result结构数组 - sizeof 返回意外结果
【发布时间】:2018-09-01 13:09:09
【问题描述】:

我的代码中声明了一组简单结构。一种 sizeof() 返回的响应与数组的大小不匹配。是否有其他方式可以声明它以确保正确的 sizeof 响应?

struct control_cmd {
    const char * cmd;
    void (*cmd_fn)(int,char *(*)[],char*);
};

struct control_cmd control_cmds[]={
    {"ANNOUNCE",control_announce},
    {"SEND",control_send}
};

sizeof(control_cmds) 在我期望 2 的值时返回 16 的值。

发生了什么事?

【问题讨论】:

    标签: c struct sizeof


    【解决方案1】:

    sizeof 是内存中的大小,而不是元素的数量。如果是数组(不是指针!),您可以通过将数组的大小除以单个元素的大小来获得元素的数量,即sizeof(control_cmds) / sizeof(*control_cmds)

    【讨论】:

    • 也就是说,在您的机器上,每个 struct control_cmd 是 8 个字节(= 2 × 32 位,它包含的两个指针)。在数组control_cmds 中有两个,所以它的大小是 2 × 8 = 16 字节。由于它是一个数组,而不仅仅是指向其第一个元素的指针,因此您可以使用sizeof(control_cmds) 来找出它的总大小,这里是 16,但是对于计数,您需要将其除以 sizeof(struct control_cmd),可以表示为sizeof(*control_cmds) as *control_cmds 是第一个元素(这里实际上并没有访问,只是使用了一种方便的方式来获取其类型的大小)。
    【解决方案2】:

    我会键入control_cmd_t,将control_cmds 声明为control_cmd_t 的数组,然后将两者相除。 (非常类似于 Arkku 的回答)。

    #include <stdio.h>
    
    typedef struct control_cmd_t__ {
        const char * cmd;
        void (*cmd_fn)(int,char *(*)[],char*);
    } control_cmd_t;
    
    control_cmd_t control_cmds[]={
        {"ANNOUNCE",control_announce},
        {"SEND",control_send}
    };
    
    int main()
    {
        printf("sizeof control_cmd_t is: %ld\n", sizeof(control_cmd_t));
        printf("sizeof control_cmds is: %ld\n", sizeof(control_cmds));
        printf("number of elements in control_cmds is: %d", (sizeof(control_cmds)/sizeof(control_cmd_t)));
    
        return 0;
    }
    

    输出:

    sizeof control_cmd_t is: 16
    sizeof control_cmds is: 32
    number of elements in control_cmds is: 2
    

    【讨论】:

    • 我认为 OP 是在询问数组的大小,而不是数组中单个元素的大小,只是巧合的是,他们的预期结果 (2) 也是元素 (struct control_cmd)。
    • 正确。我对 control_cmd_t 的大小不感兴趣 - 我想知道数组中有多少元素。
    • 感谢@Arkku 和马克。我误解了OP的问题。我已经相应地编辑了我的答案。
    猜你喜欢
    • 2021-06-10
    • 2011-09-04
    • 2010-12-26
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多