简体   繁体   中英

clone a wchar_t* in c++

I want to clone a path 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM