user2002287
user2002287

Reputation: 51

wstring to const wchar* using c_str()

I'm trying to convert a wstring to const wchar*, but the null terminations aren't working as I expect:

index 4

index 5

code

Is there any way to convert wstring to const wchar* in the manner that I'm trying?

Upvotes: 1

Views: 3670

Answers (1)

bames53
bames53

Reputation: 88235

Both works[5] and doesntWork[5] cause undefined behavior. The buffers are only valid up to [4], and [5] is outside that.

const wchar_t *works = L"Test";

works[0] -> L'T'
works[1] -> L'e'
works[2] -> L's'
works[3] -> L't'
works[4] -> L'\0'
works[5] -> undefined behavior, the program is broken if it ever tries to access this

Upvotes: 3

Related Questions