简体   繁体   English

如果没有创建该结构的对象,sizeof 如何确定内存中结构的确切大小?

[英]How can sizeof determine the exact size of a structure im memory if no object of this structure has been created?

I came across an issue by determining the size of a structure.我通过确定结构的大小遇到了一个问题。 I´ve found out that it is possible to determine the size of a structure with the preceded keyword struct inside of the sizeof-operation, although no object has been created for the respective structure:我发现可以在 sizeof 操作中使用前面的关键字struct来确定结构的大小,尽管尚未为相应的结构创建对象:

Example:例子:

#include <stdio.h>

int main()
{
   struct struct1
   {
        char a[20];
        int v,i;
        double grw;
   };

   printf("Size of struct1 in Byte: %lu",sizeof(struct struct1));

   return 0;
}

Output:输出:

Size of struct1 in Byte: 40

How is that possible?这怎么可能?

How can sizeof determine the size of a structure with the help of the struct keyword inside of the sizeof-operation, if no object of this structure has been created?如果尚未创建此结构的对象,则 sizeof 如何借助 sizeof 操作中的struct关键字确定结构的大小?

Or has been an struct1 object created, I did not know about?或者已经创建了一个struct1对象,我不知道?

I´ve thought a structure is only a datatype, but not an object of its own type.我认为结构只是一种数据类型,而不是它自己类型的对象。

Other than variable length arrays, sizeof does not need an instance of the type to figure out its size, it can work it out just based on the type definition itself.除了变长数组, sizeof不需要类型的实例计算出它的大小,它可以只基于该类型定义本身做得出来。

In the case you give (shown below), it actually knows, just from that type definition, how big the object will be (the size of each individual field plus whatever padding is needed for alignment between each field and after the final field) - the comments give one possibility:在您给出的情况下(如下所示),它实际上仅从该类型定义中就知道对象有多大(每个单独字段的大小加上每个字段之间和最终字段之后对齐所需的任何填充)-评论给出了一种可能性:

struct struct1 {
    char a[20];  // 20 bytes @ 0.
    int v,i;     // Two 4-byte values @ 20 (a multiple of 4, so already aligned).
                 // 4 bytes padding to align next 8-byte double.
    double grw;  // 8 bytes @ 32 (a multiple of 8, aligned due to padding above).
};

sizeof needs to be able to determine the size of different types otherwise it wouldn't know how much space to allocate when you do need to. sizeof需要能够确定不同类型的大小,否则它不知道在您需要时分配多少空间。

The struct definition indicates how much space is going to be used. struct定义指示将使用多少空间。

One allocation might be like this:一种分配可能是这样的:

  • char a[20] : 20 bytes. char a[20] :20 个字节。
  • int c, i : 16bit each, so 4 bytes. int c, i : 每个 16 位,所以 4 个字节。
  • double grw : 128bit, so 16 bytes. double grw :128 位,所以 16 字节。

Total: 40 bytes总计:40 字节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM