使用sizeof()计算内存容量的问题

来源:互联网 发布:md 3d软件 编辑:程序博客网 时间:2024/04/30 08:05


困扰了多日的问题,今天终于解决了,问题出在sizeof()函数上。

问题的现象:
在使用wcscpy_s对TCHAR*变量进行赋值时,提示内存空间太小。

出错信息见下图

 

errno_t wcscpy_s(   wchar_t *strDestination,//Location of destination string buffer   size_t numberOfElements,//Size of the destination string buffer   const wchar_t *strSource //Null-terminated source string buffer);


 

问题的原因:

TCHAR *stringA=new TCHAR[100];wcscpy_s(stringA,sizeof(stringA),"abcd");//对stringA进行赋值时,出错

 

sizeof(stringA)的值是4,小于字符粗"abcd"的长度(长度为5),所以提示以上错误信息。
sizeof(stringA)的值实际上是sizeof(TCHAR*)的值,而不是stringA所指向的内存空间的长度。

在林锐的《高质量C++/C编程指南》7.3.3节中有详细介绍,之前也看过几遍,但是在用的时候还是出错了。

原创粉丝点击