Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of type "const char *" cannot be assigned to an entity of type "LPSTR"

Tags:

c++

visual-c++

This question may already be having an answer but I felt I needed to ask it because I cant seem to get the answer I need for the code to work as intended on VS Community 2017 since it worked well on VS Express Edition.

I am trying to implement a code i picked up from a c project but I can't see how to get around the error:

Value of type "const char *" cannot be assigned to an entity of type "LPSTR"

and

cannot convert from 'const char [7]' to 'LPSTR'

    MENUITEMINFO mii = { 0 };

    mii.cbSize = sizeof(MENUITEMINFO);
    mii.fMask = MIIM_TYPE;
    mii.fType = MFT_STRING;
    mii.dwTypeData = _T("item 1"); // error is on this line
    mii.dwTypeData = _T("item 2"); // error is on this line also

NOTE:

  1. This is c code now on c++ project. It worked in VS Express Edition but cant compile on VS Community 2017
  2. VS Express Edition I simply changed Character set to Multi byte and it worked but on VS Community 2017 nothing seems to work and I can't see how to fix the code itself
like image 207
Jack Siro Avatar asked Apr 02 '19 11:04

Jack Siro


1 Answers

A string literal is of type const char[N], its contents must not be modified. The ability to implicitly convert string literals to char* was only ever there in C++ for backwards compatibility with C. It's a very dangerous thing, has been deprecated basically forever, and was finally removed in C++11. Visual Studio 2017 switched the default language standard to C++14, which is most likely the reason why your code stopped working there. If you absolutely, positively, definitely know for sure that the string pointed to won't be modified, then you can use a const_cast

MENUITEMINFO mii = { 0 };

mii.cbSize = sizeof(MENUITEMINFO);
mii.fMask = MIIM_TYPE;
mii.fType = MFT_STRING;
mii.dwTypeData = const_cast<char*>("item 1");

Ideally, you would just use const char*, but interop with some old C APIs, unfortunately, sometimes requires the use of const_cast. Before you do this sort of thing, always check the API documentation to make sure that there is no way the API will attempt to modify the contents of the string.

In the case of your MENUITEMINFO here, the reason why the dwTypeData is a char* rather than a const char* is most likely that the struct is intended to be used with both GetMenuItemInfo and SetMenuItemInfo where the former expects a pointer to a buffer in which it will write a string while the latter expects a pointer to a buffer from which it will read a string…

like image 160
Michael Kenzel Avatar answered Nov 13 '22 21:11

Michael Kenzel