在 struct 声明的结尾处使用[1]的目的是什么?

我在查看 MSP430微控制器的头文件时,在 <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是一个只有一个成员的数组(这个匿名结构) ,但是我无法想象它的用途。有什么想法吗?

3697 次浏览

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 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.