wchar t - Returning a wchar_t in C++ -
i'm making function return pointer wchar_t, returns nothing each time use it.
function:
wchar_t *character::getcharhealth() { wchar_t charhealth[256]; swprintf_s(charhealth, l"%d", this->gethealth()); wprintf(l"%s\n", charhealth); wchar_t* chealth = charhealth; return chealth; }
the gethealth() function:
int character::gethealth() { return this->health; }
where used:
spritefont->drawstring(spritebatch.get(), warrior->getcharhealth(), directx::simplemath::vector2(40, 0));
is there wrong code?
you returning pointer array that's out of scope, that's, wchar_t charhealth[256]
belongs getcharhealth()
once it's done running it's undefined behaviour access charhealth
array again.
what try allocate dynamic buffer charhealth
, return instead:
wchar_t *character::getcharhealth() { wchar_t* charhealth = new wchar_t[256]; swprintf_s(charhealth, l"%d", this->gethealth()); wprintf(l"%s\n", charhealth); return charhealth; }
you must remember delete[]
when no longer needed:
wchar_t* chealth = warrior->getcharhealth(); spritefont->drawstring(spritebatch.get(), chealth, directx::simplemath::vector2(40, 0)); delete[] chealth;
that's error prone might forget delete[]
. instead use std::unique_ptr<wchar_t[]>
automatically deletes pointer on destruction. that's technique called raii if no familiar with.
but really, should use std::wstring
std::to_wstring
convert number int
std::wstring
, since such object contains proper string storage optimizations , takes care of allocation might necessary.
std::wstring character::getcharhealth() { std::wstring charhealth = std::to_wstring(this->gethealth()); wprintf(l"%s\n", charhealth.c_str()); return charhealth; }
to access raw const wchar_t*
std::wstring
should use .c_str()
method, so:
spritefont->drawstring(spritebatch.get(), warrior->getcharhealth().c_str(), directx::simplemath::vector2(40, 0));
Comments
Post a Comment