bobbyalex
bobbyalex

Reputation: 2751

Cannot convert from 'const wchar_t *' to '_TCHAR *'

_TCHAR* strGroupName = NULL;
const _TCHAR* strTempName = NULL;

//Assign some value to strTempName

strGroupName = _tcschr(strTempName, 92) //C2440

I get an error at the above line while compiling this code in VS2008. In VC6 it compiles fine.

Error C2440: '=' : cannot convert from 'const wchar_t *' to '_TCHAR *'

What seems to be the problem and how do I fix it?

Upvotes: 7

Views: 22309

Answers (5)

Blenm
Blenm

Reputation: 86

I got the same error when moving from C++14->20, was able to fix it by setting /Zc:StrictStrings- under CommandLine in my build properties.

Upvotes: 1

Naveen
Naveen

Reputation: 73443

_tcschr is returning a const pointer. Hence the return value should be const _TCHAR* strGroupName = NULL; If it is not possible to change strGroupName to a const pointer then declare both the pointers as non-const pointers.

Upvotes: 2

James Hopkin
James Hopkin

Reputation: 13973

strGroupName should also be a pointer to const.

const _TCHAR* strGroupName = _tcschr(strTempName, 92);

No need to declare it until the call to initialise it.

Upvotes: 2

Cătălin Pitiș
Cătălin Pitiș

Reputation: 14341

strGroupName = const_cast<_TCHAR*>( _tcschr(strTempName, 92));

This is because the variant of the function you're using has a const _TCHAR* as input and returns a const _TCHAR*.

Another variant would be to have strTempName declared as _TCHAR*, and not as const _TCHAR*. In this case, the variant function having a _TCHAR* parameter and returning a _TCHAR* value is used.

Upvotes: 8

Jack B Nimble
Jack B Nimble

Reputation: 5087

Try casting it as

strGroupName = (_TCHAR*)_tcschr(strTempName, 92);

Seems to me that VS2008 got a little more strict on type casts, and won't automatically do them in some cases.

Upvotes: 8

Related Questions