_countof 매크로

정적으로 할당된 배열의 요소 수를 계산합니다.

구문

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

매개 변수

array
배열 이름입니다.

반환 값

배열의 요소 수이며 size_t로 표현됩니다.

설명

_countof 는 함수와 유사한 전처리기 매크로로 구현됩니다. C++ 버전에는 정적으로 선언된 배열 대신 포인터가 전달되는 경우 컴파일 시간에 검색할 수 있는 추가 템플릿 기계가 있습니다.

array는 실제로 포인터가 아니라 배열입니다. C _countof 에서는 포인터인 경우 array 잘못된 결과를 생성합니다. C++ _countof 에서 포인터인 경우 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) = %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 연산자