I have seen the usage of this statement in driver programs at the end of the structure. Can anyone explain me what is the use of this statement? and how does it works internally? I mean will compiler considers it as array or a variable?
Asked
Active
Viewed 525 times
1
-
I guess it is for struct hack. [read this](http://stackoverflow.com/q/3711233/2549281) – Dabo Apr 22 '14 at 08:50
-
That's the [struct hack](http://stackoverflow.com/questions/16553542/c-struct-hack-at-work). Nowadays you'd use [Flexible Array Members](http://stackoverflow.com/questions/246977/flexible-array-members-in-c-bad) instead. – pmg Apr 22 '14 at 08:51
2 Answers
2
In C, it's a trick to allow you to put a variable-sized array at the end of a structure, by allocating enough memory for both the fixed-sized fields and whatever you want in the array. For example:
struct array {
size_t size;
int a[]; // strictly, it should be incomplete rather than zero sized
};
struct array * make_array(size_t size) {
struct array * array = malloc(sizeof (struct array) + size * sizeof (int));
array->size = size;
return array;
}
struct array * array = make_array(2);
array->a[1] = 42; // No problem: there's enough memory for two array elements
In C++, it's not valid. Use std::vector
instead.

Mike Seymour
- 249,747
- 28
- 448
- 644
0
While arrays of size 0 are not supported by either standard, many compilers allow them as an extension. The standardised C way (C99+) instead leaves out the size altogether.
Thiis is used to describe a data-structure consisting of the starting fields and a variable number of array elements, as well as for comfortable access to them.

Deduplicator
- 44,692
- 7
- 66
- 118