PRB: sizeof Returns Nonzero Value for Zero-Sized Array

ID: Q115852

The information in this article applies to:

SYMPTOMS

The sizeof() operator will return a nonzero value when asked for the size of a zero-length array of any data type. A zero-sized array is legal only when the array is the last field in a struct or union. This syntax is specific to Microsoft, therefore, the /Ze compiler option (enable Microsoft Extentions) must be used.

This behavior is by design. In C, sizeof() must return the number of bytes necessary to tile the object in an array. Since each pointer must be unique, the size must be non-zero.

MORE INFORMATION

The sample below can be used to illustrate this problem. If you use warning level 4 (/W4 option), the following warning message will be reported:

   warning C4200: nonstandard extension used : zero-sized array in
   struct/union

Sample Code

/* Compile options needed: none
*/ 

#include <stdio.h>

struct A {
   int a[0];
};

void main(void)
{
   if( (int)(sizeof(struct A)) != 0 )
      printf( "Failed\n" );
   else
      printf( "Passed\n" );
}

Additional query words: 7.00 8.00 8.00c 9.00 1.00 1.50 2.00

Keywords          : kb16bitonly kbCompiler 
Version           : 7.00   | 1.00 1.50 | 1.00 2.00 4
Platform          : MS-DOS NT WINDOWS
Issue type        : kbprb

Last Reviewed: July 21, 1997