How to assign a value to a TCHAR array

Etan picture Etan · Oct 10, 2009 · Viewed 44.7k times · Source

I have a TCHAR array in my C++ code which I want to assign static strings to it.

I set an initial string to it via

TCHAR myVariable[260] = TEXT("initial value");

Everything works fine on this. However, when I split it in two lines as in

TCHAR myVariable[260];
myVariable = TEXT("initial value");

it bugs and gives a compiler error:

error C2440: '=': cannot convert from 'const char [14]' to 'TCHAR [260]'

shouldn't the TEXT() function do exactly what I want here? convert the given string to TCHARs? Why does it work, when putting the two lines together? What do I have to change in order to get it working?

Some other confusing thing I have encountered:

I've searched the internet for it and have seen that there are also _T() and _TEXT() and __T() and __TEXT(). What are they for? Which of them should I use in what environment?

Answer

avakar picture avakar · Oct 10, 2009

The reason the assignment doesn't work has very little to do with TCHARs and _T. The following won't work either.

char var[260];
var = "str";   // fails

The reason is that in C and C++ you can't assign arrays directly. Instead, you have to copy the elements one by one (using, for example, strcpy, or in your case _tcscpy).

strcpy(var, "str");

Regarding the second part of your question, TEXT, _T and the others are macros, that in Unicode builds turn a string literal to a wide-string literal. In non-Unicode builds they do nothing.