What is the purpose of this [1] at the end of the structure declaration?

I was browsing my MSP430 microcontroller header files, and I came across 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 */ 

I understand that it declares an anonymous structure and typedef for jmp_buf , but I canโ€™t understand what it is for [1] . I know that jmp_buf declared as an array with one member (of this anonymous structure), but I cannot imagine what it is used for. Any ideas?

+86
c struct declaration reverse-engineering
Nov 02 '17 at 23:52
source share
1 answer

This is a common trick to make a โ€œreference typeโ€ in C, where using it as an argument to a function causes one element array to degrade to a pointer to its first element without the need for a programmer to explicitly use the & operator to get its address. If declared, this is the real type of the stack (dynamic allocation is not required), but when passed as an argument, the called function receives a pointer to it, not a copy, so it went cheap (and can be changed by the called function if there is no const ).

GMP uses the same trick with its type mpz_t , and it is critical there because the structure controls a pointer to dynamically allocated memory; The mpz_init function relies on getting a pointer to a structure, not a copy of it, or cannot initialize it at all. Similarly, many operations can change the size of dynamically allocated memory, and this will not work if they cannot change the structure of the calling object.

+103
Nov 02 '17 at 23:56 on
source share



All Articles