PRB: sizeof Returns Nonzero Value for Zero-Sized Array

Last reviewed: July 18, 1997
Article ID: Q115852

The information in this article applies to:
  • The Microsoft C/C++ Compiler (CL.EXE), included with:

        - Microsoft C/C++ for MS-DOS, version 7.0
        - Microsoft Visual C++ for Windows, versions 1.0 and 1.5
        - Microsoft Visual C++, 32-bit Edition, versions 1.0, 2.0, 4.0
    

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 : CLIss kb16bitonly kbtool
Version : 7.00 | 1.00 1.50 | 1.00 2.00 4
Platform : MS-DOS NT WINDOWS
Issue type : kbprb


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: July 18, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.