宽窄字节字符串的使用

1、宽窄字符串类型指针的定义:
● 窄字节:char *p_str = "hello";
● Unicode宽字节:wchar_t *p_wstr = L"hello";
● 通用类型:TCHAR *p_tstr = _T("hello"); 或者 TCHAR *p_tstr= _TEXT("hello");
● 动态申请内存:TCHAR *pszBuf = new TCHAR[100];

其中,_TEXT 和 _T 是一样的,定义如下:
#define _T(x)       __T(x)
#define _TEXT(x)    __T(x)

来看看 __T 的最终定义:
#ifdef  _UNICODE
#define __T(x)      L##x
#else
#define __T(x)      x
#endif

其中,##为连接的意思。

2、常用的宽窄字节字符串处理函数:
字符串长度:
● Ansi:strlen(char *str);
● Unicode:wcslen(wchar_t *str);
● 通用函数:_tcslen(TCHAR *str);

● Ansi:int atoi(const char *str);
● Unicode:int _wtoi(const wchar_t *str);
● 通用函数:_tstoi(const TCHAR *str);

字符串拷贝:
● Ansi:strcpy(char *strDestination, const char *strSource);
● Unicode:wcscpy(wchar_t *strDestination, const wchar_t *strSource);
● 通用函数:_tcscpy(TCHAR *strDestination, const TCHAR *strSource);

以上函数不安全,在vs2003等以上版本的编译器中会有warnning警告提示,以下为安全函数(VC++6.0不支持):
● Ansi:strcpy_s(char *strDestination, size_t numberOfElements, const char *strSource);
● Unicode:wcscpy_s(wchar_t *strDestination, size_t numberOfElements, const wchar_t *strSource);
● 通用函数:_tcscpy_s(TCHAR *strDestination, size_t numberOfElements, const TCHAR *strSource);

numberOfElements
Size of the destination string buffer. 目的缓冲区的大小,以字节为单位,不是字符!

size_t unsigned integer,在MSDN中的解释:Result of sizeof operator,也就是说 size_t 是 unsigned integer 即无符号整数。那为什么会有size_t这个类型呢?
因为不同平台的操作系统(32/64)中 int/long 等类型所占的字节并不一样,而 size_t 在不同的平台下有不同的定义。有点类似于TCHAR类型:
#ifndef   _SIZE_T_DEFINED
  #ifdef     _WIN64
  typedef   unsigned   __int64         size_t;   //8个字节,64位
  #else
  typedef   _W64   unsigned   int       size_t;   //4个字节,32位
  #endif
  #define   _SIZE_T_DEFINED
#endif

3、sizeof 求宽窄字节字符串的注意事项:
char* p_str = "hello";
我想求这个字符串所占用的字节数:sizeof(p_str) 肯定是错误的!
strlen(p_str) + 1,实际上就是 p_str 指针指向的字符串所占用的空间对吧?因为本身1个char占用1个字节的存储空间,所以默认字符串的长度加上字符串的结束符 \0 就是字符串所占用的字节数。

那么宽字节呢?wchar_t* p_wstr = L"hello";
他占用的字节数应该如何来求?
wcslen(p_str) + 1 这个对吗?当然也是不对的,正确的是:(wcslen(p_str) + 1) * sizeof(wchar_t)

通用类型:TCHAR* p_tstr = _T("hello");
(_tcslen(p_tstr) + 1) * sizeof(TCHAR)

应用在哪里呢?比如:
TCHAR *pszBuf = new TCHAR[100];
定义完了之后,我要给这个字符串数组清空,于是我应该这么做:
memset(pszBuf, 0, 100 * sizeof(TCHAR)) 这样做是最安全的,不管当前的 TCHAR 是 char 也好,是 wchar_t 也好,都可以满足。
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值