计算静态分配的数组中元素的个数。
_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
}