1. 程式人生 > >_countof、sizeof、strlen的區別和用法

_countof、sizeof、strlen的區別和用法

1  countof:是系統定義的一個巨集,求取元素的陣列的元素個數

2  sizeof:運算子,在標頭檔案中typedefunsigned int,其值在編譯時即計算好了,獲得保證能容納實現所建立的最大物件的位元組大小

3 strlen:是一個函式,在執行時執行,返回字串的長度。該字串可能是自己定義的,也可能是記憶體中隨機的,該函式實際完成的功能是從代表該字串的第一個地址開始遍歷,直到遇到結束符NULL。返回的長度大小不包括NULL

// 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(arr):40個位元組  _countof(arr):20個元素