Share via


_countof 巨集

計算靜態配置陣列中的專案數目。

語法

#define _countof(array) (sizeof(array) / sizeof(array[0]))

參數

array
陣列的名稱。

傳回值

陣列中的元素數目,表示為 size_t

備註

_countof 會實作為類似函式的預處理器宏。 C++ 版本具有額外的範本機制,以在編譯時期偵測是否傳遞指標,而不是靜態宣告的陣列。

請確定 array 實際上是陣列,而不是指標。 在 C 中,如果 array 為指標, _countof 則會產生錯誤的結果。 在 C++ 中,如果 array 是指標, _countof 則無法編譯。 當做參數傳遞至函式的陣列會衰落至 指標 ,這表示在函式內,您無法用來 _countof 判斷陣列的範圍。

需求

Macro 必要的標頭
_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) = %zu bytes\n", sizeof(arr) );
   printf( "_countof(arr) = %zu elements\n", _countof(arr) );
   // In C++, the following line would generate a compile-time error:
   // printf( "%zu\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 運算子