Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wchar_t pointer

What's wrong with this:

wchar_t * t = new wchar_t;

t = "Tony";

I thought I could use a wchar_t pointer as a string...

like image 541
Tony The Lion Avatar asked Jun 24 '10 17:06

Tony The Lion


People also ask

What is wchar_t C++?

The wchar_t type is an implementation-defined wide character type. In the Microsoft compiler, it represents a 16-bit wide character used to store Unicode encoded as UTF-16LE, the native character type on Windows operating systems.

What is the default value of array data type wchar_t?

The default value for wchar_t is zero so there's no need to even give any values in the brackets.


2 Answers

A pointer just points to a single value. This is important.

All you've done is allocated room for a single wchar_t, and point at it. Then you try to set the pointer to point at a string (remember, just at the first character), but the string type is incorrect.

What you have is a string of char, it "should" be L"Tony". But all you're doing here is leaking your previous memory allocation because the pointer holds a new value.

Rather you want to allocate enough room to hold the entire string, then copy the string into that allocated memory. This is terrible practice, though; never do anything that makes you need to explicitly free memory.

Just use std::wstring and move on. std::wstring t = L"Tony";. It handles all the details, and you don't need to worry about cleaning anything up.

like image 105
GManNickG Avatar answered Sep 17 '22 09:09

GManNickG


Since you are a C# developer I will point out a few things c++ does different.

This allocates a new wchar_t and assigns it to t

wchar_t* t = new wchar_t

This is an array of constant char

"Tony" 

To get a constant wchar_t array prefix it with L

L"Tony"

This reasigns t to point to the constant L"Tony" instead of your old wchar_t and causes a memory leak since your wchar_t will never be released.

t = L"Tony"

This creates a string of wide chars (wchar_t) to hold a copy of L"Tony"

std::wstring t = L"Tony"

I think the last line is what you want. If you need access to the wchar_t pointer use t.c_str(). Note that c++ strings are mutable and are copied on each assignment.

The c way to do this would be

const wchar_t* t = L"Tony"

This does not create a copy and only assigns the pointer to point to the const wchar array

like image 36
josefx Avatar answered Sep 20 '22 09:09

josefx