_countof、sizeof、strlen的区别和用法

来源:互联网 发布:软件 poc测试方案 编辑:程序博客网 时间:2024/06/05 17:52

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个元素


0 0