struct声明末尾的[1]的目的是什么? [英] What's the purpose of this [1] at the end of struct declaration?

查看:88
本文介绍了struct声明末尾的[1]的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在窥探MSP430微控制器的头文件,然后在< setjmp.h> 中遇到了这个问题:

I was snooping through my MSP430 microcontroller's header files, and I ran into this in <setjmp.h>:

/* r3 does not have to be saved */
typedef struct
{
    uint32_t __j_pc; /* return address */
    uint32_t __j_sp; /* r1 stack pointer */
    uint32_t __j_sr; /* r2 status register */
    uint32_t __j_r4;
    uint32_t __j_r5;
    uint32_t __j_r6;
    uint32_t __j_r7;
    uint32_t __j_r8;
    uint32_t __j_r9;
    uint32_t __j_r10;
    uint32_t __j_r11;
} jmp_buf[1]; /* size = 20 bytes */

我知道它声明了一个匿名结构,并将typedef定义为 jmp_buf ,但我不知道 [1] 是干什么的。我知道它声明 jmp_buf 是一个具有一个成员(此匿名结构的成员)的数组,但是我无法想象它的用途。有任何想法吗?

I understand that it declares an anonymous struct and typedef's it to jmp_buf, but I can't figure out what the [1] is for. I know it declares jmp_buf to be an array with one member (of this anonymous struct), but I can't imagine what it's used for. Any ideas?

推荐答案

这是在C中将引用类型用作函数参数的常见技巧。导致单元素数组降级为指向其第一个元素的指针,而程序员无需显式使用& 运算符来获取其地址。在声明的地方,它是一个真正的堆栈类型(不需要动态分配),但是当作为参数传递时,被调用函数会收到指向它的指针,而不是副本,因此它被廉价地传递(如果没有,则可以由被调用函数进行突变 const )。

This is a common trick to make a "reference type" in C, where using it as a function argument causes the single element array to degrade to a pointer to its first element without the programmer needing to explicitly use the & operator to get its address. Where declared, it's a real stack type (no dynamic allocation needed), but when passed as an argument, the called function receives a pointer to it, not a copy, so it's passed cheaply (and can be mutated by the called function if not const).

GMP对 mpz_t 类型,在这里很关键,因为该结构管理着指向动态分配内存的指针; mpz_init 函数依赖于获取结构的指针,而不是结构的副本,或者根本无法初始化它。同样,许多操作可以调整动态分配的内存的大小,并且如果它们不能使调用者的结构发生突变,则将无法正常工作。

GMP uses the same trick with its mpz_t type, and it's critical there, because the structure manages a pointer to dynamically allocated memory; the mpz_init function relies on getting a pointer to the structure, not a copy of it, or it couldn't initialize it at all. Similarly, many operations can resize the dynamically allocated memory, and that wouldn't work if they couldn't mutate the caller's struct.

这篇关于struct声明末尾的[1]的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆