您的位置:首页 > 其它

_countof、sizeof、strlen的区别和用法

2014-03-12 22:25 423 查看
1 countof:是系统定义的一个宏,求取元素的数组的元素个数

2 sizeof:运算符,在头文件中typedef为unsigned
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个元素
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: