如题怎么才能转换呢
CString str="hello!"
char str1[255]="\0";
strncpy(str1,str,str.GetLength()+1) //这句不通过
------解决方案--------------------
char* pstr = str.GetBuffer(str.GetLength());
strncpy(pstr,&str1,str.GetLength()+1);
------解决方案--------------------
是把CSting的内容复制给char str1[255],为什么不能用指针?
------解决方案--------------------
'strncpy': This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
------解决方案--------------------
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_t count );
举例:
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);