sách gpt4 ăn đã đi

c - 结构中未调整大小的数组声明

In lại 作者:太空狗 更新时间:2023-10-29 16:40:52 26 4
mua khóa gpt4 giày nike

Tại sao C 允许这样做:

typedef struct s{ int arr[];} s;

mảng arr 没有指定大小?

câu trả lời hay nhất

这是称为灵活数组 的 C99 功能,主要功能是允许 use variable length array like features inside a structR.. 在这个answer to another question on flexible array members提供了使用灵活数组 而非con trỏ 的好处列表。 draft C99 standardhiện hữu 6.7.2.1 Structure and union specifiers 段落 16 中说:

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply. [...]

因此,如果您有一个 s*,除了 cấu trúc 所需的空间之外,您还需要为数组分配空间,通常结构中还有其他成员:

s *s1 = malloc( sizeof(struct s) + n*sizeof(int) ) ;

标准草案实际上在 17 段中有一个具有启发性的示例:

EXAMPLE After the declaration:

  struct s { int n; double d[]; };

the structure struct S has a flexible array member ngày. A typical way to use this is:

   int m = /* some value */;
struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));

and assuming that the call to trung tâm succeeds, the object pointed to by P behaves, for most purposes, as if P had been declared as:

    struct { int n; double d[m]; } *p;

(there are circumstances in which this equivalence is broken; in particular, the offsets of member ngày might not be the same).

关于c - 结构中未调整大小的数组声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20221012/

26 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress