CString赋值给char数组

1.传给未分配内存的const char* (LPCTSTR)指针.

CString cstr(asdd);

const char* ch = (LPCTSTR)cstr;

ch指向的地址和cstr相同。但由于使用const保证ch不会修改,所以安全.

2.传给未分配内存的指针.

CString cstr = "ASDDSD";

char *ch = cstr.GetBuffer(cstr1.GetLength() + 1);

cstr.ReleaseBuffer();

//修改ch指向的值等于修改cstr里面的值.

//PS:用完ch后,不用delete ch,因为这样会破坏cstr内部空间,容易造成程序崩溃.

3.第二种用法。把CString 值赋给已分配内存的char *。

CString cstr1 = "ASDDSD";

int strLength = cstr1.GetLength() + 1;

char *pValue = new char[strLength];

strncpy(pValue, cstr1, strLength);

4.第三种用法.把CString 值赋给已分配内存char[]数组.

CString cstr2 = "ASDDSD";

int strLength1 = cstr1.GetLength() + 1;

char chArray[100];

memset(chArray,0, sizeof(bool) * 100); //将数组的垃圾内容清空.

strncpy(chArray, cstr1, strLength1);


在VC2008中使用时,不再使用strncpy函数,而使用更为安全的strncpy_s函数。函数原型是

errno_t strncpy_s( char *strDest, size_t numberOfElements, const char *strSource, size_tcount );

举例:

      char *p = "hello who you are ? ";
       char *dest;
	char s[20]; 	
	dest = (char *) malloc (sizeof (char) * 1000);
	//if we use strncpy_s we will get assert
	//for the size is not enough
	//we can just change s[20] to s[21]
	strncpy_s(s, _countof(s), p, strlen(p));
	printf("%s\n", s);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值