次の方法で共有

Facebook x.com LinkedIn 電子メール

_countof マクロ

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

_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 Operator


  • Last updated on 2011年08月09日