Array of Zero Length
In C , it is possible to define structs containing zero length arrays. This is referred to as a C-Hack and can be useful in certain situations.
Case Study
A recent code refactoring revealed several structs with zero length arrays, such as:
struct someData { int nData; BYTE byData[0]; }
Why Zero Length Arrays?
Usually, a compiler generates a warning for zero length arrays, but in this case, the warnings were suppressed. One possible reason for using zero length arrays is to allow for the creation of an array of any length at runtime.
Creating Structures with Zero Length Arrays
Attempting to create a new structure with a zero length array using the "new" operator will result in an error. Instead, the following technique can be used:
struct someData* mallocSomeData(int size) { struct someData* result = (struct someData*)malloc(sizeof(struct someData) + size * sizeof(BYTE)); if (result) { result->nData = size; } return result; }
This function allocates memory for an object of type someData and its byData array of the specified size.
Alternative Approaches
In many cases, a more appropriate approach would be to use a pointer or an array of length 1 instead of a zero length array. This would eliminate the need for the custom memory allocation and make the code more readable and maintainable.
Conclusion
Zero length arrays can be a useful technique in certain situations, but they should be used with caution. In most cases, alternative approaches, such as pointers or arrays of length 1, are more appropriate and would make the code more straightforward to understand and maintain.
The above is the detailed content of Why Use Zero-Length Arrays in C Structs?. For more information, please follow other related articles on the PHP Chinese website!