次の方法で共有


_countof マクロ

更新 : 2007 年 11 月

静的に割り当てられた配列の要素数を計算します。

_countof( 
      array
);

パラメータ

  • array
    オブジェクトの名前。

戻り値

配列の要素数。

解説

array にはポインタではなく、実際の配列を指定するようにしてください。C では、array にポインタを指定すると、_countof は誤った結果を生成します。C++ では、array にポインタを指定すると、_countof を正常にコンパイルできません。

必要条件

マクロ

必須ヘッダー

_countof

<stdlib.h>

使用例

// crt_countof.cpp
#define _UNICODE
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>

int main( void )
{
   _TCHAR arr[20], *p;
   printf( "sizeof(arr) = %d bytes\n", sizeof(arr) );
   printf( "_countof(arr) = %d elements\n", _countof(arr) );
   // In C++, the following line would generate a compile-time error:
   // printf( "%d\n", _countof(p) ); // error C2784 (because p is a pointer)

   _tcscpy_s( arr, _countof(arr), _T("a string") );
   // unlike sizeof, _countof works here for both narrow- and wide-character strings
}

sizeof(arr) = 40 bytes
_countof(arr) = 20 elements

参照

参照

sizeof Operator