Last member in structs type T [1] instead of T *

I saw the following code in the project I am working on:

struct Str { size_t count; T data[1]; }; Str* str = (Str*)malloc(sizeof(Str) + sizeof(T) * count); str->count = count ... 

str->data used as an array with count elements of T from this point.

Why declare T data[1] instead of T* data ? Is there any benefit to this?

0
source share
1 answer

Your code is invalid C ++.

However, it is valid C, a kind of. The standard way to write this to C is to declare the final element as T data[]; ("flexible length array"), and the goal is to allow you to allocate one separate dynamic memory block and store both a fixed header and a variable-length array in it together.

There are several restrictions on the use of this type (for example, it cannot be a type of an automatic variable or an array element). See, for example, the implementation of GCC , which offers several non-standard extensions.

+2
source

Source: https://habr.com/ru/post/958851/


All Articles