C 结构类型[1]是什么意思?

C 结构类型[1]是什么意思?,c,struct,sizeof,C,Struct,Sizeof,我发现一些代码的结构大小如下: sizeof(struct struct_type[1]); 我进行了测试,它确实返回了struct\u type的大小 及 返回结构大小的两倍 编辑: struct\u type是一个结构,而不是数组: struct struct_type { int a; int b; }; struct\u type[1]实际上是什么意思?记住sizeof语法: sizeof ( typename ); 这里的typename是struct struc

我发现一些代码的结构大小如下:

sizeof(struct struct_type[1]);
我进行了测试,它确实返回了
struct\u type
的大小

返回结构大小的两倍

编辑:

struct\u type
是一个结构,而不是数组:

struct struct_type {
    int a;
    int b;
};

struct\u type[1]
实际上是什么意思?

记住
sizeof
语法:

sizeof ( typename );
这里的typename是
struct struct\u type[N]
或更可读的形式
struct struct\u type[N]
,它是struct struct\u type类型的N个对象的数组。正如您所知,数组大小是一个元素的大小乘以元素总数。

就像:

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

因此:

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

这里的
struct-struct-type[1]
struct-struct-type[2]
只是表示
struct-struct-type
类型的元素的
数组
,而
sizeof
只是返回那些表示的数组的大小。

对于声明

int arr[10];
可以使用
arr
作为操作数或
int[10]
计算数组大小。由于
sizeof
运算符根据操作数的类型生成大小,因此
sizeof(arr)
sizeof(int[10])
都将返回数组的大小
arr
(最终
arr
的类型是
int[10]

C11-§6.5.3.3/2:

sizeof运算符生成其操作数的大小(以字节为单位),该操作数可以是 表达式或类型的括号名称大小由操作数的类型决定。结果是一个整数。如果操作数的类型是可变长度数组类型,则对操作数求值;否则,不计算操作数,结果为整数常量

类似地,对于
struct-struct\u类型的数组

struct struct_type a[1];

大小可以通过
sizeof(a)
sizeof(struct-struct\u type[1])
计算

struct_type
可能是一个结构数组,
sizeof(struct-struct_type[1])
获取结构数组中第一个元素的大小。@i如果不是,它不是数组,请查看我的更新如何声明
结构类型的数组
?现在想想如何按类型获得该数组的大小。这通常不是好的做法,因为最好将对象的大小设置为
sizeof
,即变量或取消引用指向该类型的指针。这样,如果更改对象的类型,代码就不会中断。另一个问题是在代码中使用整数常量(也称为“幻数”)。错误的做法是,使用
#define
(又称宏)。在
int a[5]之后,我们得到
sizeof(int)==4,sizeof(int[5])==20,sizeof(a)==20,sizeof(a[5])==4
。合乎逻辑<代码>:-)
不,它不会。它甚至不会编译。您不能在
sizeof
@Doddy;不。一点也不。@Doddy数组在作为参数传递给函数时衰减为指针。这不会发生在
sizeof
运算符上
sizeof
是一个运算符,而不是函数。如果仍然有疑问,请在您的系统中进行验证。@Doddy,这没关系;我已经疯了好几个世纪了。:)@Doddy:FWIW,我倾向于同意,给出任何带有
sizeof
的例子都是不好的做法,会导致人们做各种奇怪的、破烂的废话。
sizeof(struct struct_type[2]); // return size of 2 `struct struct_type'
int arr[10];
struct struct_type a[1];