I know C++ has converter. But to know how memory is working i should know why i can not do that:
#include <iostream>
#include <cstring>
int main() {
const char* text = "hello";
std::wstring* wtext = malloc(5);
strcpy(wtext, text);
std::wcout << wtext << std::endl;
free(wtext);
return 0;
}
"text" is pointer of "hello"
"wtext" is pointer of memory which contains free 5 bytes
function "strcpy" copies memory from pointer "text" to pointer "wtext"
"std::wcout" is printing out this all
"free" cleans old memory of pointer "wtext" \
If all of this theory is right ,then it should be working, but it is not.
Why can not i resize something and put it into this one?
so C++ compiler says i can not use "malloc" on "wtext" because it has not the same types of variable. However, professor says pointers can have any things in it, because it is pointers. They can point at numbers, text, e.t.c. I did not understand what had happened.
You should never allocate C++ objects with malloc
(nor deallocate with free
).
malloc
is a legacy from C. It only allocates raw memory and does not call the proper constructor.
In C++ you should (in principle) use new
to dynamically allocate an object and get a pointer to it (and delete
to deallocate).
In practice there are rare cases where you actually need to use raw pointers with manual new
/delete
. Usually using a smart pointer will be better.
But in the case of wstring
there's no reason to use any kind of pointer at all. Just use the object directly.
Also if you make text
a char
array, you can use std::begin
and std::end
to initialize the wstring
:
#include <string>
#include <iostream>
int main()
{
const char text[] = "hello";
std::wstring wtext(std::begin(text), std::end(text));
std::wcout << wtext << std::endl;
}
Output:
hello
Note:
Reading your question and code example, I assumed your source string contains only ascii characters.
If this is not the case, you cannot simply initialize wtext
from text
as shown above. Instead you will need to use some API to convert it, like std::wstring_convert
, std::mbstowcs
etc. These documentation links also show some usage examples.