I want to clone a pat开发者_运维问答h that is held in a var named szPath to a new wchar_t.
szPath is of the type wchar_t *. so i tried doing something like:
szPathNew = *szPath;
but this is referring to the same place in memory. what should i do? i want to deep clone it.
Do this,
wchar_t clone[260];
wcscpy(clone,szPath);
Or, if you want to allocate memory yourself,
wchar_t *clone = new wchar_t[wcslen(szPath)+1];
wcscpy(clone,szPath);
//use it
delete []clone;
Check out : strcpy, wcscpy, _mbscpy at MSDN
However, if your implementation doesn't necessarily require raw pointers/array, then you should prefer this,
#include<string>
//MOST SAFE!
std:wstring clone(szPath);
Do not use raw C strings in C++. If you want wide character strings, you can use std::wstring:
#include <string>
...
std::wstring szPathClone1 = szPath; // Works as expected
If you insist on using wchar_t buffers directly, you can use the wcscpy function.
PS: You also seem to be confused by pointer usage, you should first learn more about pointers.
The _wcsdup
function duplicates (clones) a string. Note that this allocates new memory, so you will need to free it later:
wchar_t * szPathClone = _wcsdup(szPath);
// ...
free(szPathClone);
精彩评论