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

查看:21
本文介绍了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天全站免登陆