共用方式為


_countof 巨集

計算以靜態方式配置的陣列中的項目數。

_countof( 
   array
);

參數

  • array
    陣列中的名稱。

傳回值

陣列中的項目數。

備註

請確定array是實際的陣列,不是指標。 在 c 中, _countof會產生錯誤的結果,如果array是一個指標。 在 C++ 中, _countof將無法編譯如果array是一個指標。

需求

巨集

所需的標頭

_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 運算子