Home > Backend Development > C++ > Why Use Zero-Length Arrays in C Structs?

Why Use Zero-Length Arrays in C Structs?

Mary-Kate Olsen
Release: 2024-12-11 10:05:15
Original
582 people have browsed it

Why Use Zero-Length Arrays in C Structs?

Array of Zero Length

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];
}
Copy after login

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;
}
Copy after login

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:

  • Pointers: Replace the zero-length array with a direct pointer to the buffer and allocate the buffer separately.
  • Arrays of Length 1: Create an array of length 1 and use the first element as a pointer to the buffer.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template