Export (0) Print
Expand All

Unsized Arrays in Structures

A Microsoft extension allows the last member of a C or C++ structure or class to be a variable-sized array. These are called unsized arrays. The unsized array at the end of the structure allows you to append a variable-sized string or other array, thus avoiding the run-time execution cost of a pointer dereference.

// unsized_arrays_in_structures1.cpp
// compile with: /c
struct PERSON {
   unsigned number;
   char name[];   // Unsized array
};

If you apply the sizeof operator to this structure, the ending array size is considered to be 0. The size of this structure is 2 bytes, which is the size of the unsigned member. To get the true size of a variable of type PERSON, you would need to obtain the array size separately.

The size of the structure is added to the size of the array to get the total size to be allocated. After allocation, the array is copied to the array member of the structure, as shown below:

// unsized_arrays_in_structures2.cpp
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

enum {
   sizeOfBuffer = 40
};

struct PERSON {
   unsigned number;
   char name[];   // Unsized array
};

int main() {
   char szWho[sizeOfBuffer];
   PERSON *ptrPerson = NULL;

   printf_s( "Enter name: " );
   gets_s( szWho, sizeOfBuffer );
 
   // Allocate space for structure, name, and terminating null
   ptrPerson = (PERSON *)malloc( sizeof( struct PERSON ) 
                           + strlen( szWho ) + 1 );

   // Copy the string to the name member
   strcpy_s( ptrPerson->name, sizeOfBuffer, szWho );
}

Input

John

Even after the structure variable's array is initialized, the sizeof operator returns the size of the variable without the array.

Structures with unsized arrays can be initialized, but arrays of such structures cannot be initialized.

struct PERSON me  = { 6, "Me" };        // Legal
struct PERSON you = { 7, "You" };

struct PERSON us[2] = { { 8, "Them" },  // Error
                        { 9, "We" } };

An array of characters initialized with a string literal gets space for the terminating null; an array initialized with individual characters (for example, {'a', 'b', 'c'}) does not.

A structure with an unsized array can appear in other structures, as long as it is the last member declared in its enclosing structure. Classes or structures with unsized arrays cannot have direct or indirect virtual bases.

For related information, see volatile and #define.

Community Additions

ADD
Show:
© 2014 Microsoft