简体   繁体   English

struct_type [1]是什么意思?

[英]What does struct_type[1] mean?

I found some code that gets the size of struct like this: 我找到了一些像这样得到struct大小的代码:

sizeof(struct struct_type[1]);

I tested and it does return the size of struct_type . 我测试过它确实返回了struct_type的大小。

And

sizeof(struct struct_type[2]);

returns twice the struct size. 返回结构大小的两倍。

Edit: 编辑:

struct_type is a struct, not an array: struct_type是一个结构,而不是一个数组:

struct struct_type {
    int a;
    int b;
};

What does struct_type[1] actually mean? struct_type[1]实际上是什么意思?

Remember sizeof syntax: 记住sizeof语法:

sizeof ( typename );

Here typename is struct struct_type[N] or in more readable form struct struct_type [N] which is an array of N objects of type struct struct_type. 这里typename是struct struct_type[N]或更易读的struct struct_type [N] ,它是一个类型为struct struct_type的N个对象的数组。 As you know array size is the size of one element multiplied by the total number of elements. 如您所知,数组大小是一个元素的大小乘以元素的总数。

Just like: 就像:

sizeof(int[1]); // will return the size of 1 int

and

sizeof(int[2]); // will return the size of 2 ints

So does: 那样做:

sizeof(struct struct_type[1]); // return size of 1 `struct struct_type'

and

sizeof(struct struct_type[2]); // return size of 2 `struct struct_type'

Here struct struct_type[1] , and struct struct_type[2] simply represent arrays of elements of type struct struct_type , and sizeof of is just returning the size of those represented arrays. 这里struct struct_type[1]struct struct_type[2]只表示struct struct_type类型的元素arrays ,而sizeof只是返回那些表示数组的大小。

For the declaration 为宣言

int arr[10];

size of array can be calculated by either using arr as an operand or int [10] . 数组的大小可以通过使用arr作为操作数或int [10]来计算。 Since sizeof operator yields the size based on the type of operand, both sizeof(arr) and sizeof (int [10]) will return the size of array arr (ultimately arr is of type int [10] ). 由于sizeof运算符根据操作数的类型生成大小,因此sizeof(arr)sizeof (int [10])将返回数组arr的大小(最终arr的类型为int [10] )。

C11-§6.5.3.3/2: C11-§6.5.3.3/ 2:

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. sizeof运算符产生其操作数的大小(以字节为单位),该操作数可以是表达式或类型的带括号的名称。 The size is determined from the type of the operand . 大小由操作数的类型确定 The result is an integer. 结果是整数。 If the type of the operand is a variable length array type, the operand is evaluated; 如果操作数的类型是可变长度数组类型,则计算操作数; otherwise, the operand is not evaluated and the result is an integer constant. 否则,不评估操作数,结果是整数常量。

Similarly, for an array of struct struct_type 类似地,对于struct struct_type的数组

struct struct_type a[1];

size can be calculated either by sizeof (a) or sizeof(struct struct_type[1]) . size可以通过sizeof (a)sizeof(struct struct_type[1])

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

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