Refactoring old code can uncover questionable practices, like the use of zero-length arrays in structs. This prompts the question: Why create an array with no elements?
Consider the following struct:
struct someData { int nData; BYTE byData[0]; }
A zero-length array, as seen in byData, is an unusual choice. Typically, arrays store elements. However, arrays of length 0 can be used as pointers. In this case, byData serves as a placeholder for a variable-length buffer that will be dynamically allocated later.
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 a someData struct and a buffer of the specified length. The zero-length array in the struct allows us to treat it as a pointer, referencing the dynamically allocated buffer.
To refactor this code, consider using:
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!